본문 바로가기
알고리즘

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();
	}
}


'알고리즘' 카테고리의 다른 글

SPFA (Shortest Path Faster Algorithm)  (0) 2018.07.17
인덱스 트리 (Indexed Tree)  (0) 2018.07.17
플로이드 워셜 (Floyd Warshall)  (0) 2018.07.17
다익스트라 (Dijkstra)  (0) 2018.07.17
DFS, BFS  (0) 2018.07.17
컨벡스 헐 (Convex hull)  (0) 2018.07.17
이분탐색 (Binary Search)  (0) 2018.07.17
CCW  (0) 2017.12.12