알고리즘
DFS (Stack)
by 출근길
2018. 7. 17.
package graph;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
import java.util.StringTokenizer;
public class DFS_stack {
/*
* DFS, BFS
*/
public static void main(String[] args) throws IOException {
//System.setIn(new FileInputStream("res/preTest/coin.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int T = Integer.parseInt(br.readLine().trim());
for (int Ti = 1; Ti <= T; Ti++){
int N = Integer.parseInt(br.readLine().trim());
boolean[] VISIT = new boolean[N];
ArrayList[] NODE = new ArrayList[N];
for (int i = 0; i < N; i++){
NODE[i] = new ArrayList();
}
StringTokenizer ST = new StringTokenizer(br.readLine());
int root = 0;
for (int i = 0; i < N; i++){
int a = Integer.parseInt(ST.nextToken());
NODE[a].add(i);
}
Stack STK = new Stack();
STK.push(root);
VISIT[root] = true;
while (!STK.isEmpty()) {
boolean flag = true;
int edge = STK.peek();
for (int next : NODE[edge]) {
if (!VISIT[next]) {
STK.push(next);
//VISIT 체크
VISIT[next] = true;
flag = false;
break;
}
}
if (flag) {
//POP시에 비교작업
STK.pop();
}
}
int RESULT = Integer.MAX_VALUE;
bw.write("#" + Ti + " " + RESULT + "\n");
}
br.close();
bw.flush();
bw.close();
}
}