본문 바로가기
프로그래밍 언어/알고리즘 및 디자인패턴

BFS(너비 우선 탐색)

by Mostlove 2023. 7. 16.
728x90
반응형

namespace Exercise
{
    internal class Program
    {
        class Graph
        {
            int[,] adj = new int[6, 6]
            {{0,1,0,1,0,0},
             {1,0,1,1,0,0},
             {0,1,0,0,0,0},
             {1,1,0,0,1,0},
             {0,0,0,1,0,1},
             {0,0,0,0,1,0}};
            List<int>[] adj2 = new List<int>[]
            {
                new List<int>{ 1, 3 },
                new List<int>{ 0, 2, 3 },
                new List<int>{ 1 },
                new List<int>{ 0, 1, 4 },
                new List<int>{ 3, 5 },
                new List<int>{ 4 },
            };

            public void BFS(int start)//길찾기에서 쓰임
            {
                bool[] found = new bool[6];
                int[] parent = new int[6];
                int[] distance = new int[6];
                Queue<int> q = new Queue<int>();
                q.Enqueue(start);
                found[start] = true;
                parent[start] = start;
                distance[start] = 0;

                while(q.Count > 0)
                {
                    int now = q.Dequeue();
                    Console.WriteLine(now);

                    for (int next = 0; next < 6; next++)
                    {
                        if (adj[now, next] == 0)
                            continue;
                        if (found[next])
                            continue;
                        q.Enqueue(next);
                        found[next] = true;
                        parent[next] = now;
                        distance[next] = distance[now]+1;
                    }
                }
            }

        
        };

        static void Main(string[] args)
        {
            //DFS(Depth First Search 깊이 우선 탐색)
            //BFS(Breadth First Search 너비 우선 탐색)
            Graph graph = new Graph();
            graph.BFS(0);
        }
    }
}

반응형

'프로그래밍 언어 > 알고리즘 및 디자인패턴' 카테고리의 다른 글

다익스트라 최단 경로 알고리즘  (0) 2023.07.16
BFS를 이용한 길찾기 구현  (0) 2023.07.16
DFS(깊이 우선 탐색)  (0) 2023.07.16
그래프 생성  (0) 2023.07.16
그래프 이론  (0) 2023.07.16