110 likes | 256 Views
Chapter 4. 4 Basic Algorithms Binary Search Depth-First Search Breadth-First Search Topological Sort. Advanced Algorithms. DFS Testing Whether a Graph is Connected BFS Finding the shorted path BFS or DFS Solving a maze. Binary Search. int bsearch(L, i , j, key) {
E N D
Chapter 4 • 4 Basic Algorithms • Binary Search • Depth-First Search • Breadth-First Search • Topological Sort
Advanced Algorithms • DFS Testing Whether a Graph is Connected • BFS Finding the shorted path • BFS or DFS Solving a maze.
Binary Search int bsearch(L, i , j, key) { while (i <= j) { k = (i+j)/2; if (key == L[k]) return k; // Found if (key < L[k]) j = k-1; else i = k+1; } return –1 // Not found } key = 31 i k j 57 i j k 57
adj is an arry of linked lists: adj[0] 2 3 null adj[1] 1 4 null adj[2] 1 4 ... trav is a linked list dfs (adj, start) { n = adj.size(); for i = 0 to n-1 visit[i] = false; dfs_rec(adj, start); } dfs_rec (adj, cur) { print(cur); visit[cur] = true; trav = adj[cur]; while (trav != null) { v = trav.vertex(); if (!visit[v]) dfs_rec(adj, v); trav = trav.next(); } } DFS
q is an initially empty queue adj is an array of linked lists trav is a linked list visit is an array of bool bfs (adj, start) { n = adj.size(); for i = 0 to n-1 { visit[i] = false; print(start); visit[start] = true; q.push(start); while (!q.empty()) { cur = q.pop(); trav = adj[cur]; while (trav != null) { v = trav.vertex(); if (!visit[v]) { print(v) visit[v] = true; q.push(v); } trav = trav.next(); } } } BFS
Maze Problem S F
Maze Problem S B C A D E G L I H M K J N W X O V Y Z U P Q T R F
Maze Problem S A B C D E G L I H M K J N W X Y O V Z U P Q R T F
Maze Problem S A B C D E G L I H M K J N W X Y O V Z U P Q R T F
Maze Problem S A B C D E G L I H M K J N W X Y O V Z U P Q R T F
ts is a stack; topsort (adj, ts) { n = adj.size(); k = n; for i = 0 to n-1 visit[i] = false; for i = 0 to n-1 if (!visit[i]) tsr(adj,i,ts); } tsr (adj, cur, ts) { visit[cur] = true; trav = adj[cur]; while (trav != null) { v = trav.vertex(); if (!visit[v]) tsr(adj, v, ts); trav = trav.next(); } ts.push(cur); } Topological Sort