BFS - create a queue Queue<Integer> q = new...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
public class BFS { private static int gcd(int a,int b) { if (a==0) return b; if (b==0) return a; return gcd(b,a%b); } private static boolean coprime(int a,int b) { return gcd(a,b)==1; } public static void print(GraphList G) { System.out.println("List of edges:"); for (int u=0; u<G.getNumVertices(); u++) { // traverse through neigbors of u int v; for (int k=1; (v=G.kth_Adjacent(u,k)) >=0; k++) if (u<v) // print each edge only once System.out.print(" ["+u+","+v+"]"); System.out.println(); } } public static void visit(int node) { System.out.println("Visiting node "+node); } public static void BreadthFirstSearch(GraphList G, int start) { System.out.println("Performing breadth first search starting in vertex " +start); int n = G.getNumVertices(); // create an array where we mark visited vertices boolean[] visited = new boolean[n]; // initialized to false
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // create a queue Queue<Integer> q = new Queue<Integer>(); q.enqueue(new Integer(start)); visit(start); visited[start] = true; while (!q.isEmpty()) { Integer current = q.dequeue(); int v; for (int k=1; (v=G.kth_Adjacent(current.intValue(),k)) >=0; k++) if (!visited[v]) { q.enqueue(new Integer(v)); visit(v); visited[v] = true; } } } public static void main(String args) { GraphList G = new GraphList(10); // graph with 10 vertices // add some edges for (int u=0; u<G.getNumVertices(); u++) for (int v=u+1; v<G.getNumVertices(); v++) if (coprime(u,v)) G.addEdge(u,v); // remove some edges for (int u=2; u<G.getNumVertices(); u++) G.removeEdge(u-2,u); print(G); BreadthFirstSearch(G,0); BreadthFirstSearch(G,9); } }...
View Full Document

This note was uploaded on 04/26/2010 for the course CMPT 225 taught by Professor Annelavergne during the Spring '07 term at Simon Fraser.

Page1 / 2

BFS - create a queue Queue<Integer> q = new...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online