SMALL

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net


  • 문제


  • 문제풀이

정점의 수, 간선의 수, 시작 정점을 받아준 후 간선정보를 입력한 뒤 각각 BFS와 DFS를 시행해준다.

 


  • 코드 1
namespace YONGYONG2
{
    using System;
    using System.Collections.Generic;

    
    public class Program
    {
        static int N;
        static int[,] Graph;
        static bool[] DFSbool;
        static bool[] BFSbool;
        public static void DFS(int N,int V)
        {
            DFSbool[V] = true;
            Console.Write(V + " ");
            for(int i=1;i<=N;i++)
            {
                if (Graph[V, i] == 1 && !DFSbool[i])
                {
                    DFS(N,i);
                }
            }
        }
        public static void BFS(int N,int V)
        {
            Queue<int> queue = new Queue<int>();
            queue.Enqueue(V);
            BFSbool[V] = true;
            Console.Write(V + " ");
            while (queue.Count != 0)
            {
                int temp= queue.Dequeue();
                for(int i = 1; i <= N; i++)
                {
                    if (Graph[temp, i] == 1 && !BFSbool[i])
                    {
                        queue.Enqueue(i);
                        Console.Write(i+" ");
                        BFSbool[i] = true;
                    }
                }
            }
        }
        public static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            N = int.Parse(input[0]);
            int M = int.Parse(input[1]);
            int V = int.Parse(input[2]);
            Graph= new int[N+1, N+1];
            DFSbool=new bool[N+1];
            BFSbool = new bool[N + 1];
            for(int i = 0; i < M; i++)
            {
                string[] line = Console.ReadLine().Split();
                int a = int.Parse(line[0]);
                int b = int.Parse(line[1]);
                Graph[a, b] = 1;
                Graph[b, a] = 1;
            }

            DFS(N, V);
            Console.WriteLine();
            BFS(N, V);

        }
    }

}

 


  • 후기

DFS와 BFS는 잊으면 안되겠다.

LIST

+ Recent posts