코딩테스트/백준

1260번 DFS와 BFS

Cadi 2025. 7. 20. 15:15

코딩테스트 : 1260번 DFS와 BFS

DFS와 BFS 성공

 
시간 제한메모리 제한제출정답맞힌 사람정답 비율
2 초 128 MB 337665 136150 80369 38.849%

문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

입력

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

using System.Data;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Text;

public class BackJoon
{
    private static StringBuilder sb;
    
    static bool[]  visited;
    public static void Main()
    {
        int[] NMV = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        int N = NMV[0];
        int M = NMV[1];
        int V = NMV[2];
        
       visited = new bool[N+1];
        
        List<int>[] array = new List<int>[N+1];

        for (int i = 0; i <= N; i++)
        {
            array[i] = new List<int>();
        }
        for (int i = 0; i < M; i++)
        {
            int[] row = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            array[row[0]].Add(row[1]);
            array[row[1]].Add(row[0]);
        }
        for (int i = 0; i <= N; i++)
        {
            array[i].Sort(); 
        }
        sb = new StringBuilder();
        DFS(V, array);
        sb.AppendLine();
        visited = new bool[N+1];
        BFS(V, array);
        Console.WriteLine(sb.ToString());
        
    }

    public static void DFS(int index, List<int>[] array)
    {
        sb.Append(index+" ");
        visited[index] = true;
        foreach (int startIndex in array[index])
        {
            if (visited[startIndex] == false)
            {
                visited[startIndex] = true;
                DFS(startIndex, array);
            }
        }
    }

    public static void BFS(int index, List<int>[] array)
    {
        Queue<int> queue = new Queue<int>();

        queue.Enqueue(index);
        visited[index] = true;
        while (queue.Count > 0)
        {
            int current = queue.Dequeue();
            sb.Append(current + " ");
            foreach (int nextIndex in array[current] )
            {
                if (!visited[nextIndex])
                {
                    visited[nextIndex] = true;
                    queue.Enqueue(nextIndex);
                }
            }
        }
        
    }
}

정렬하는 것을 놓쳐서 한 번 틀렸다.