1 / 11

Chapter 4

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) {

tamera
Download Presentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 • 4 Basic Algorithms • Binary Search • Depth-First Search • Breadth-First Search • Topological Sort

  2. Advanced Algorithms • DFS  Testing Whether a Graph is Connected • BFS  Finding the shorted path • BFS or DFS  Solving a maze.

  3. 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

  4. 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

  5. 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

  6. Maze Problem S F

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

More Related