본문 바로가기

프로그래밍/Java

자바 양방향 그래프 dfs - 2차원 행렬, 반복문, 스택, LinkedHashSet

728x90
반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] line = reader.readLine().split("\\s+");    // 7, 8
        int vertex = Integer.parseInt(line[0]);    // 노드
        int edge = Integer.parseInt(line[1]);    // 간선

        int[][] adjMatrix = new int[vertex + 1][vertex + 1];
        for (int[] matrix : adjMatrix) {
            Arrays.fill(matrix, 0);    // 2차원 행렬 초기화
        }

        for (int i = 0; i < edge; i++) {
            line = reader.readLine().split("\\s+");

            /*
            1 2
            1 3
            2 4
            2 5
            4 6
            5 6
            6 7
            3 7
            */

            int start = Integer.parseInt(line[0]);
            int end = Integer.parseInt(line[1]);
            adjMatrix[start][end] = 1;
            adjMatrix[end][start] = 1;    // 양방향 그래프
        }

        Stack<Integer> stack = new Stack<>();    // 현재 진행중인 스택
        stack.add(1);    // 처음 시작할 순서
        Set<Integer> visited = new LinkedHashSet<>();    // 방문했던 노드를 저장할 Set, 순서대로 출력할것이기에 LinkedHashSet 사용

        while (!stack.isEmpty()) {
            int current = stack.pop();
            visited.add(current);    // 노드를 방문했다고 추가

            for (int i = 0; i < vertex + 1; i++) {
                if (adjMatrix[current][i] == 1 && !visited.contains(i)) {
                    stack.add(i);    // 이어져있고 방문하지 않았으면 스택에 추가
                }
            }
        }

        for (Integer i : visited) {
            System.out.print(i + " ");    // 1 3 7 6 5 2 4 
        }
    }
}
728x90
반응형