Professional Documents
Culture Documents
Edges
Each edge connects two vertices: (i,j) = edge between i and j Undirected graphs: the edge (i,j) is equivalent to the edge (j,i) Directed graphs: the edges are directed (they are sometimes called arcs) => i->j is different from j->i (although they both connect i and j) We will only consider graphs where no edge occurs twice (and there are no loops)
Both vertices and edges can have extra information associated to them (e.g. name, cost) Graphs can be used for modeling many structures, for example:
Road networks Social relationships
Graph Representations
Adjacency matrix
A = an NxN matrix A[i][j] = 1 if the edge (i,j) occurs in the graph (i.e. the vertices i and j are connected by an edge), and 0 otherwise for undirected graphs A[i][j] = 1 if there is a directed arc from i to j for directed graphs A is symmetrical (A[i][j] == A[j][i]) for undirected graphs
Lists of neighbors
An array of N linked-lists The list L[i] contains all the neighbors of the vertex i In the case of directed graphs, the neighbors of a vertex are considered to be those nodes j such that the arch i->j exists
(Simplifying) Assumptions
No multiple edges (i,j) No loops (i,i)
Graph Traversals
Depth-First Search (DFS)
Mark all the vertices as not visited Starting vertex S => call dfs(S) dfs(x)
Mark x as visited For y in Neighbors(X):
If (y has not been marked as visited) then call dfs(y)
N = numNodes;
// allocate the adjacency matrix A = new char*[N]; for (i = 0; i < N; i++) A[i] = new char[N];
template<typename TnodeInfo, typename TedgeInfo> class Graph { public: int N; LinkedList<struct list_elem_info<TedgeInfo> > *L; TnodeInfo *nodeInfo;