-
Notifications
You must be signed in to change notification settings - Fork 290
/
Copy pathDFS_graph.java
90 lines (81 loc) · 2.67 KB
/
DFS_graph.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Stack;
class DFSgraph{
static Scanner sc;
public static void main(String args[]){
try{
File file = new File("C:\\Users\\Tanisha\\Desktop\\dfs_input.txt");
sc = new Scanner(file);
}
catch(Exception e){
System.out.println("Error");
System.out.println(e.getMessage());
}
String initialInfo;
if(sc.hasNextLine())
initialInfo = sc.next();
else initialInfo = "";
String[] arr = initialInfo.split(",");
int n = Integer.parseInt(arr[0]);
ArrayList<Integer>[] graph = new ArrayList[n];
for(int i=0; i<n; i++) {
graph[i] = new ArrayList<>();
}
sc.next();
if(arr[1].equals("u")){
while (sc.hasNext()){
String s = sc.next();
graph[s.charAt(0)-97].add(s.charAt(2)-97);
graph[s.charAt(2)-97].add(s.charAt(0)-97);
}
}
else if(arr[1].equals("d")){
while (sc.hasNext()){
String s = sc.next();
graph[((int)s.charAt(0)-97)].add(s.charAt(2)-97);
}
}
try{
PrintStream ps = new PrintStream(new File("out_dfs.txt"));
PrintStream console = System.out;
System.setOut(ps);
dfs(graph);
//System.out.println(k.substring(k.length()-1));
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void dfs(ArrayList<Integer>[] graph){
Stack<Integer> st = new Stack<>();
int count = 0;
boolean[] vis = new boolean[graph.length];
st.push(0);
while(!st.isEmpty()){
int curr_vtx = st.pop();
vis[curr_vtx]=true;
if(count==graph.length){
System.out.print(((char)(curr_vtx+'a'))+" ");
return;
}
System.out.print(((char)(curr_vtx+'a')+",")+" ");
// for(int n : graph[curr_vtx]){
// if(!vis[n]){
// st.push(n);
// vis[n] = true;
// }
// }
for(int i=graph[curr_vtx].size()-1; i>=0; i--){
int n = graph[curr_vtx].get(i);
if(!vis[n]){
st.push(n);
vis[n] = true;
count++;
}
}
}
}
}