60 likes | 189 Views
Lecture 14. Graph Representations. Graph Representation. How do we represent a graph internally? Two ways adjacency matrix list Adjacency Matrix For each edge (v,w) in E, set A[v][w] = edge_cost Non existent edges with logical infinity Cost of implementation
E N D
Lecture 14 Graph Representations
Graph Representation • How do we represent a graph internally? • Two ways • adjacency matrix • list • Adjacency Matrix • For each edge (v,w) in E, set A[v][w] = edge_cost • Non existent edges with logical infinity • Cost of implementation • O(|V|2) time for initialization • O(|V|2) space • ok for dense graphs • unacceptable for sparse graphs
Graph Class (Matrix representation) Public class Graph public static final double NO_EDGE; Graph() {} Graph(int n) {} public void SetSize(int n); public void AddEdge(int origin, int destination, double value); public void RemoveEdge(int origin, int destination); public boolean HasEdge(int origin, int destination) ; public double EdgeValue(int origin, int destination) ; int NumNodes() {} int NumEdges() {} private int myNumEdges; private int [][] M; };
Graph Representation • Adjacency List • Ideal solution for sparse graphs • For each vertex keep a list of all adjacent vertices • Adjacent vertices are the vertices that are connected to the vertex directly by an edge. • Example List 0 List 1 List 2 Draw the graph ?? 1 2 2 0 1 1
Graph Representation ctd.. • The number of list nodes equals to number of edges • O(|E|) space • Space is also required to store the lists • O(|V|) for |V| lists • Note that the number of edges is at least round(|V|/2) • assuming each vertex is in some edge • Therefore disregard any O(|V|) term when O(|E|) is present • Adjacency list can be constructed in linear time (wrt to edges) • More on this when we learn pointers
Graph Algorithms • Graphs depend on two parameters • edges (E) • Vertices (V) • Graph algorithms can be complicated to analyze • One algorithm might be order (V2) • for dense graphs • Another might be order((E+V)log E) • for sparse graphs • Depth First Search • Is the graph connected? If not what are their connected components? • Does the graph have a cycle? • How do we examine (visit) every node and every edge systematically? • First select a vertex, set all vertices connected to that vertex to non-zero • Find a vertex that has not been visited and repeat the step above • Repeat above until all zero vertices are examined.