490 likes | 498 Views
Learn about the main types of graphs and two implementation approaches. Also, get a reminder about trees.
E N D
6. Intro. to Graphs Introduce the main kinds of graphs, discuss two implementation approaches, and remind you about trees Contest Algorithms: 6. Intro. to Graphs
1. Graph Terms • (Strongly) Connected Component • Sub Graph • Complete Graph • Directed Acyclic Graph (DAG) • Tree/Forest • Euler/Hamiltonian Path/Cycle • Bipartite Graph • Vertices/Nodes • Edges • Un/Weighted • Un/Directed • In/Out Degree • Self-Loop/Multiple Edges • Sparse/Dense • Path, Cycle • Isolated, Reachable Contest Algorithms: 6. Graph Intro
A graph has two parts (V, E), where: • V are the nodes, called vertices • E are the links between vertices, called edges 849 PVD ORD 1843 142 SFO 802 LGA 1743 337 1387 HNL 2555 1099 1233 LAX 1120 DFW MIA
Directedgraph • the edges are directed • e.g., bus cost network • Undirectedgraph • the edges are undirected • e.g., road network
A weighted graph adds edge numbers. 8 b a 6 2 6 4 c 3 d 5 9 12 4 e
V a b h j U d X Z c e i W g f Y • End vertices (or endpoints) of an edge • U and V are the endpoints • Edges incident on a vertex • a, d, and b are incident • Adjacent vertices • U and V are adjacent • Degree of a vertex • X has degree 5 • Parallel edges • h and i are parallel edges • Self-loop • j is a self-loop
Path • sequence of alternating vertices and edges • begins with a vertex • ends with a vertex • each edge is preceded and followed by its endpoints • Simple path • path such that all its vertices and edges are distinct • Examples • P1=(V,b,X,h,Z) is a simple path • P2=(U,c,W,e,X,g,Y,f,W,d,V) is a path that is not simple V b a P1 d U X Z P2 h c e W g f Y
Cycle • circular sequence of alternating vertices and edges • each edge is preceded and followed by its endpoints • Simple cycle • cycle such that all its vertices and edges are distinct • Examples • C1=(V,b,X,g,Y,f,W,c,U,a) is a simple cycle • C2=(U,c,W,e,X,g,Y,f,W,d,V,a,) is a cycle that is not simple V a b d U X Z C2 h e C1 c W g f Y Graphs
A graph is connected if there is a path between every pair of vertices Connected graph Non connected graph with two connected components
a g c d e b f Strong Connectivity • Each vertex can reach all other vertices Graphs
Complete Graphs • All pairs of vertices are connected by an edge. • No. of edges |E| = |V| (|V-1|)/2 = O(|V|2)
Some Competition Graphs • Directed Acyclic Graph • no cycle • Eulerian Graph • must visit each edge once • Tree • connected, E = V-1, unique path! • Bipartite • 2 sets, no edges within set!
Directed Acyclic Graph (DAG) • A DAG has no cycles • Some algorithms become simpler when used on DAGs instead of general graphs, based on the principle of topological ordering • find shortest paths and longest paths by processing the vertices in a topological order Contest Algorithms
Euler Graph • An Euler graph has either an Euler path or Euler tour. • An Euler path is defined as a path in a graph which visits each edge exactly once. • An Euler tour/cycle is an Euler path which starts and ends on the same vertex. Contest Algorithms: 6. Graph Intro
Bipartite graph (bigraph) • A graph whose vertices can be divided into two disjoint sets U and V • every edge connects a vertex in U to one in V Contest Algorithms: 6. Graph Intro
2. Graph-related Problems • Search/traversal • visit every node once (Euler) • visit every edge once (Hamiltonian) • Shortest paths • Minimal Spanning Trees (MSTs) • Network flow • Matching • Graph coloring • Travelling salesman problem Contest Algorithms: 6. Graph Intro
3. Implementing Graphs • Adjacency matricies • if there is an edge from i to j then ai,j = 1, otherwise ai,j = 0. • Size: O(V2); V, number of vertices • use with relatively low n and when the graph is dense (many edges) • Adjacency lists • Each node has a list of neighbors • O(V + E) (usually lower); E is the number of edges • use when the graph is sparse (few edges) Contest Algorithms: 6. Graph Intro
Edges lists • A list of edges in the graph • O(2 * E) E is the number of edges • use when the graph is sparse (few edges) Contest Algorithms: 6. Graph Intro
Examples Contest Algorithms: 6. Graph Intro
3.1. Loading a Weighted Directed Graph Into an Adjacency Matrix (v.1) 2 3 1 0 1 Adj Matrix: 2 3 1 0 0 0 0 2 3 0 3 2 0 0 2 0 0 1 0 1 0 1 0 0 0 2 1 3 3 3 2 1 1 2 4
Input data format: • no. of vertices • multiple lines, one for each vertex • each line: one number per vertex: 0 or a weight e.g. 5 2 3 1 0 0 0 0 2 3 0 3 2 0 0 2 0 0 1 0 1 0 1 0 0 0 see matData.txt Contest Algorithms: 6. Graph Intro
Code see UseAdjMatrix.java public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("matData.txt")); int numVs = sc.nextInt(); int[][] adjMat = new int[numVs][]; // use numVs as no. of rows for (int i = 0; i < numVs; i++) { adjMat[i] = new int[numVs]; // create ith row array with numVs as no. of columns for (int j = 0; j < numVs; j++) // fill row with weights adjMat[i][j] = sc.nextInt(); } printMatrix(adjMat); } // end of main() Contest Algorithms: 6. Graph Intro
public static void printMatrix(int[][] adjMat) { System.out.println("Adj Matrix:"); int numVs = adjMat.length; for (int i = 0; i < numVs; i++) { for (int j = 0; j < numVs; j++) System.out.printf(" %3d", adjMat[i][j]); System.out.println(); } System.out.println(); } // end of printMatrix() Contest Algorithms: 6. Graph Intro
Into an Adjacency Matrix (v.2) • Input data format: • no. of vertices, no. of edges • multiple lines, one for each edge • each line: (a b) weight e.g. e.g. 5 10 0 0 2 0 1 3 0 2 1 1 3 3 2 0 3 2 1 2 2 4 2 3 2 1 3 4 1 4 1 1 This is a better input format for sparse graphs which have few edges see mat2Data.txt Contest Algorithms: 6. Graph Intro
Code see UseAdjMatrix2.java public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("mat2Data.txt")); int numVs = sc.nextInt(); int numEs = sc.nextInt(); int[][] adjMat = new int[numVs][]; for (int i = 0; i < numVs; i++) adjMat[i] = new int[numVs]; for (int i = 0; i < numEs; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int weight = sc.nextInt(); adjMat[a][b] = weight; } printMatrix(adjMat); // same as before } // end of main() Contest Algorithms: 6. Graph Intro
3.2. Loading a Weighted Directed Graph Into an Adjacency List 2 3 1 0 Adj List: 0: (0, 2) (1, 3) (2, 1) 1: (3, 3) 2: (0, 3) (1, 2) (4, 2) 3: (2, 1) (4, 1) 4: (1, 1) 1 2 1 3 3 3 2 1 1 2 4
Input data format: • no. of vertices • multiple lines, one for each vertex • each line: no. of pairs, list of (vertex, weight) pairs e.g. 5 3 0 2 1 3 2 1 1 3 3 3 0 3 1 2 4 2 2 2 1 4 1 1 1 1 see adjListData.txt Contest Algorithms: 6. Graph Intro
Storing a Pair of ints see IPair.java public String toString() { return "(" + x + ", " + y + ")"; } public int compareTo(IPair ip) { if (x != ip.getX()) return (x - ip.getX()); else return (y - ip.getY()); } // end of compareTo() } // end of IPair class public class IPair implements Comparable<IPair> { private int x, y; public IPair(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public void setX(int el) { x = el; } public void setY(int el) { y = el; } Contest Algorithms: 6. Graph Intro
Code see UseAdjList.java public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("adjListData.txt")); int numVs = sc.nextInt(); ArrayList<ArrayList<IPair>> adjList = new ArrayList<>(numVs); // a list containing lists of (vertex, weight) pairs for (int i = 0; i < numVs; i++) // for each vertex adjList.add(new ArrayList<>()); // add a list to the list // fill each list with (vertex, weight) pairs for (ArrayList<IPair> neigborList : adjList) { int numNeighbors = sc.nextInt(); // get no. of pairs for (int j = 0; j < numNeighbors; j++) neigborList.add( new IPair(sc.nextInt(), sc.nextInt())); // (vertex, weight) } printAdjList(adjList); } // end of main() Contest Algorithms: 6. Graph Intro
public static void printAdjList( ArrayList<ArrayList<IPair>> adjList) { System.out.println("Adj List:"); int vCount = 0; for (ArrayList<IPair> neigborList : adjList) { System.out.print(vCount + ":"); for(IPair neigbour : neigborList) System.out.print(" " + neigbour); System.out.println(); vCount++; } System.out.println(); } // end of printAdjList() Contest Algorithms: 6. Graph Intro
3.3. Loading a Weighted Directed Graph Into an Edges List 2 Edges List, sorted into decreasing weight: (3, 0, 1) (3, 1, 3) (3, 2, 0) (2, 0, 0) (2, 2, 1) (2, 2, 4) (1, 0, 2) (1, 3, 2) (1, 3, 4) (1, 4, 1) 3 1 0 1 2 1 3 3 3 2 1 1 2 4
Input data format: • no. of edges • multiple lines, one for each edge • each line: (a, b) and weight, but data is stored weight, a, b e.g. 10 0 0 2 0 1 3 0 2 1 1 3 3 2 0 3 2 1 2 2 4 2 3 2 1 3 4 1 4 1 1 see elData.txt Contest Algorithms: 6. Graph Intro
Storing a Triple of ints see ITriple.java public String toString() { return "(" + x +", "+ y +", "+ z + ")"; } public int compareTo(ITriple t) { if (x != t.getX()) return (t.getX() - x); // decreasing order by x // return (x - t.getX()); // increasing order by x else if (y != t.getY()) return (y - t.getY()); else return (z - t.getZ()); } // end of compareTo() } // end of ITriple class public class ITriple implements Comparable<ITriple> { private int x, y, z; public ITriple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } public void setX(int el) { x = el; } public void setY(int el) { y = el; } public void setZ(int el) { z = el; } Contest Algorithms: 6. Graph Intro
Code see UseEdgesList.java public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("elData.txt")); int numEs = sc.nextInt(); PriorityQueue<ITriple> edgesList = new PriorityQueue<>(numEs); // priority queue of weighted edges; (weight, a, b) // build pri-queue of edges; (weight, a, b) for (int i = 0; i < numEs; i++) { int a = sc.nextInt(); int b = sc.nextInt(); // edge a-b int weight = sc.nextInt(); edgesList.offer( new ITriple(weight, a, b) ); } printEdgesList(edgesList); } // end of main() Contest Algorithms: 6. Graph Intro
public static void printEdgesList( PriorityQueue<ITriple> edgesList) { System.out.println("Edges List, sorted into decreasing weight: "); int numEs = edgesList.size(); for (int i = 0; i < numEs; i++) { ITriple wedge = edgesList.poll(); // weighted-edge pair System.out.println(" " + wedge); } } // end of printEdgesList() Contest Algorithms: 6. Graph Intro
3.4. Space and Time Comparisons • Space • Adjacency Matrix O( |V|2) • Adjacency List O(|V|+|E|) • Edges List O(2 * |E|) • Time • Find edge of vi and vj • Matrix (aij) O(1), List O(|V|) • Find all edges of vi • List O(|V|) but faster than matrix O(|V|) • Dense graph: (many edges) use an adj. matrix • Sparse graph: (few edges) use an adj. list (or edges list) Contest Algorithms: 6. Graph Intro
4. Trees • A tree is a special graph. It is: • Connected • Has V vertices and exactly E = V ? 1 edges • Has no cycle • Has one unique path between two vertices • Sometimes, it has one special vertex called “root” (rooted tree): Root has no parent • A vertex in n-ary tree has either {0, 1,…,n} children • n = 2 is called binary tree Contest Algorithms: 6. Graph Intro
Trees and Forests • A (free) tree is an undirected graph T such that • T is connected • T has no cycles This definition of tree is different from the one of a rooted tree • A forest is an undirected graph without cycles • The connected components of a forest are trees Tree Forest Graphs
(Rooted) Tree Terminology • e.g. Part of the ancient Greek god family: levels 0 Uranus 1 Aphrodite Kronos Atlas Prometheus 2 Eros Zeus Poseidon Hades Ares 3 Apollo Athena Hermes Heracles : :
Some Definitions • Let T be a tree with root v0. • Suppose that x, y, z are verticies in T. • (v0, v1,..., vn) is a simple path in T (no loops). • a) vn-1 is the parent of vn. • b) v0, ..., vn-1 are ancestors of vn • c) vn is a child of vn-1 continued
d) If x is an ancestor of y, then y is a descendant of x. • e) If x and y are children of z, then x and y are siblings. • f) If x has no children, then x is a terminal vertex (or a leaf). • g) If x is not a terminal vertex, then x is an internal (or branch) vertex. continued
h) The subtree of T rooted at x is the graph with vertex set V and edge set E • V contains x and all the descendents of x • E = {e | e is an edge on a simple path from x to some vertex in V} • i) The length of a path is the number of edges it uses, not verticies. continued
j) The level of a vertex x is the length of the simple path from the root to x. • k) The height of a vertex x is the length of the simple path from x to the farthest leaf • the height of a tree is the height of its root • l) A tree where every internal vertex has exactly m children is called a full m-ary tree.
Applied to the Example • The root is Uranus. • A simple path is {Uranus, Aphrodite, Eros} • The parent of Eros is Aphrodite. • The ancestors of Hermes are Zeus, Kronos, and Uranus. • The children of Zeus are Apollo, Athena, Hermes, and Heracles. continued
The descendants of Kronos are Zeus, Poseidon, Hades, Ares, Apollo, Athena, Hermes, and Heracles. • The leaves (terminal verticies) are Eros, Apollo, Athena, Hermes, Heracles, Poseidon, Hades, Ares, Atlas, and Prometheus. • The branches (internal verticies) are Uranus, Aphrodite, Kronos, and Zeus. continued
The subtree rooted at Kronos: Kronos Zeus Poseidon Hades Ares Apollo Athena Hermes Heracles continued
The length of the path {Uranus, Aphrodite, Eros} is 2 (not 3). • The level of Ares is 2. • The height of the tree is 3.