30 likes | 122 Views
CS 220 Fall 2013 Lecture 56. Recursive DFS. import java.util.Scanner; import java.io.*; public class dfs { int a[][]; boolean visited[]; public dfs(String in) { try { Scanner s = new Scanner(new File(in)); int i = s.nextInt(); int j; a = new int[i][i];
E N D
CS 220 Fall 2013 Lecture 56 Recursive DFS
import java.util.Scanner; import java.io.*; public class dfs { int a[][]; boolean visited[]; public dfs(String in) { try { Scanner s = new Scanner(new File(in)); int i = s.nextInt(); int j; a = new int[i][i]; visited = new boolean[i]; while (s.hasNextInt()) { i = s.nextInt(); j = s.nextInt(); a[i][j] = 1; a[j][i] = 1; } } catch (Exception e) {System.out.println(e.getMessage());} for (int i = 0; i < a.length; i++) visited[i] = false; }
public String dfsR() { visited[a.length-1] = true; return dfsR(a.length-1); } public String dfsR(int i) { String s = new String(""+i+" "); for (int j = 0; j < a[i].length; j++) { if (a[i][j] == 1 && !visited[j]) { visited[j] = true; s = s+dfsR(j); } } return s; }