본문 바로가기

카테고리 없음

#24 DFS

DFS는 "Depth-First Search"의 약자로, 그래프 탐색 알고리즘 중 하나입니다. 그래프는 정점(Vertex)과 간선(Edge)으로 구성되며, DFS는 이 그래프의 정점들을 탐색하는 방법 중 하나입니다. DFS는 특정 정점에서 출발하여 가능한 깊이(depth)까지 탐색한 후, 더 이상 갈 수 없게 되면 다시 돌아와서 다른 경로를 탐색하는 방식으로 작동합니다.

DFS는 주로 다음과 같은 방식으로 동작합니다

 

 

  1. 시작 정점에서 출발하여 탐색을 시작합니다.
  2. 현재 정점에서 연결된 정점 중 방문하지 않은 정점으로 이동합니다.
  3. 방문한 정점은 다시 그 정점에서 연결된 정점으로 이동하며, 더 이상 방문할 정점이 없을 때까지 반복합니다.
  4. 더 이상 방문할 정점이 없으면, 이전 정점으로 돌아와 다른 경로를 탐색합니다.
  5. 모든 정점을 방문할 때까지 2~4 과정을 반복합니다.

 

 

DFS는 스택(Stack) 자료 구조를 이용하거나 재귀(Recursive) 방식으로 구현할 수 있습니다. 스택을 사용한 비재귀 구현과 재귀 구현은 모두 DFS의 동작 원리를 잘 나타냅니다.

 

 

import java.util.ArrayList;
import java.util.List;

public class DFSRecursive {
    private static void dfs(int v, boolean[] visited, List<List<Integer>> graph) {
        visited[v] = true;
        System.out.print(v + " ");
        for (int neighbor : graph.get(v)) {
            if (!visited[neighbor]) {
                dfs(neighbor, visited, graph);
            }
        }
    }

    public static void main(String[] args) {
        int numVertices = 7; // 정점의 수
        List<List<Integer>> graph = new ArrayList<>();
        
        for (int i = 0; i < numVertices; i++) {
            graph.add(new ArrayList<>());
        }

        // 그래프를 인접 리스트로 표현
        graph.get(0).add(1);
        graph.get(0).add(2);
        graph.get(1).add(0);
        graph.get(1).add(3);
        graph.get(1).add(4);
        graph.get(2).add(0);
        graph.get(2).add(5);
        graph.get(2).add(6);
        graph.get(3).add(1);
        graph.get(4).add(1);
        graph.get(5).add(2);
        graph.get(6).add(2);

        boolean[] visited = new boolean[numVertices];
        
        // DFS 탐색 시작 (시작 정점: 0)
        dfs(0, visited, graph);
    }
}

 

 

 

 

 

스택을 이용한 비재귀 DFS:

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class DFSStack {
    private static void dfs(int start, List<List<Integer>> graph) {
        boolean[] visited = new boolean[graph.size()];
        Stack<Integer> stack = new Stack<>();
        stack.push(start);

        while (!stack.isEmpty()) {
            int v = stack.pop();
            if (!visited[v]) {
                visited[v] = true;
                System.out.print(v + " ");
                for (int i = graph.get(v).size() - 1; i >= 0; i--) {
                    int neighbor = graph.get(v).get(i);
                    if (!visited[neighbor]) {
                        stack.push(neighbor);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        int numVertices = 7; // 정점의 수
        List<List<Integer>> graph = new ArrayList<>();
        
        for (int i = 0; i < numVertices; i++) {
            graph.add(new ArrayList<>());
        }

        // 그래프를 인접 리스트로 표현
        graph.get(0).add(1);
        graph.get(0).add(2);
        graph.get(1).add(0);
        graph.get(1).add(3);
        graph.get(1).add(4);
        graph.get(2).add(0);
        graph.get(2).add(5);
        graph.get(2).add(6);
        graph.get(3).add(1);
        graph.get(4).add(1);
        graph.get(5).add(2);
        graph.get(6).add(2);

        // DFS 탐색 시작 (시작 정점: 0)
        dfs(0, graph);
    }
}

 

 

DFS는 그래프의 모든 정점을 한 번씩 방문하는데 유용하며, 경로 찾기, 사이클 검출, 연결 요소(connected components) 찾기 등에 널리 사용됩니다.