DFS - s.push(new Integer(start)); visit(start);...

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

View Full Document Right Arrow Icon
public class DFS { 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(GraphMatrix G) { System.out.println("List of edges:"); for (int u=0; u<G.getNumVertices(); u++) { // traverse through neigbors of u int v=G.nextAdjacent(u,-1); while (v>=0) { if (u<v) // print each edge only once System.out.print(" ["+u+","+v+"]"); v=G.nextAdjacent(u,v); } System.out.println(); } } public static void visit(int node) { System.out.println("Visiting node "+node); } public static void DepthFirstSearch(GraphMatrix G, int start) { System.out.println("Performing depth 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 // create a queue Stack<Integer> s = new Stack<Integer>();
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: s.push(new Integer(start)); visit(start); visited[start] = true; int last = -1; // last node from which we returned while (!s.isEmpty()) { int u = s.peek().intValue(); // the vertex at the top of stack boolean hasUnvisitedNeighbor = false; for (int v=G.nextAdjacent(u,last); v>=0; v=G.nextAdjacent(u,v)) if (!visited[v]) { s.push(new Integer(v)); visit(v); visited[v] = true; hasUnvisitedNeighbor = true; break; } if (!hasUnvisitedNeighbor) last = s.pop(); } } public static void main(String args) { GraphMatrix G = new GraphMatrix(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); DepthFirstSearch(G,0); DepthFirstSearch(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

DFS - s.push(new Integer(start)); visit(start);...

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