Why Use Adjacency Matrices or Adjacency Lists?

生来就可爱ヽ(ⅴ<●) 提交于 2020-05-15 11:38:11

问题


I've just started learning about graphs, and something that's confusing me is why we need to use external data structures (like matrices or lists) to store which vertexes of the graph are connected to other vertices.

Why can't each vertex just hold references to the vertices its connected to, like the way nodes do in a decision tree? That, to me, seems more intuitive.

Thanks!


回答1:


Well, this comes from a design philosophy. Whenever you have a many to many relationships, you introduce a broker to hold the relationship. This breaks the relationship and makes it easier to manage code and write a data structure.

For example, if we keep all the vertices (call it List B) information to a vertex (call it A) that is connected to List B, any changes in any of the vertices of List B needs to be propagated to A. If we remove some edge, we need to update that in A. This can become very messy. This also violates the Single Responsibility Principle. Now my vertex can be modified from 2 axes - if it modifies on its own or any of its connections get modified.

However, if we model our data structure such that each vertex can change independently and any change in a vertex doesn't require other vertices to be mutated, that makes our life simpler. We can have a manager or broker that manages the relationship between each vertex instead of each vertices managing that. This relationship manager is the adjacency list / adjacency matrix.




回答2:


Adjacency Matrices Or Adjacency Lists are not mandatory. There are alternatives. If you are using C++ then use vector & map. If vertex/node are numbered from 0-N then you do not need map, rather vector will do. For example:

vector < vector < int > > graph; // while vertex/node are numbered from 0-N.
map < int, vector<int> > graph; // when vertex/node can be any number

graph[i].push_back(x); // insertion of node x in i'th list. 

Traversing i'th list will show you nodes connected with node i.



来源:https://stackoverflow.com/questions/59450195/why-use-adjacency-matrices-or-adjacency-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!