본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 2667 단지번호붙이기

by 왹져박사 2023. 10. 13.
728x90

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

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

BFS 문제에 재미 붙여서 계속 찾아서 풀게 된다..! 이제는 완전히 문제를 보면 어떤 식으로 풀어나갈지 그려진다. 

이 문제에서 주의할 점은, 단지 수를 출력한 뒤에 각 단지에 속한 집의 수를 '오름차순'으로 출력해야 한다는 점이다. 

using System;
using System.IO;
using System.Text;

namespace B2667
{
    class Program
    {
        static int N;
        static int[,] map = new int[26, 26];
        static bool[,] visited = new bool[26, 26];
        static Queue<(int, int)> q = new Queue<(int, int)>();
        static int[] dx = { -1, 1, 0, 0 };
        static int[] dy = { 0, 0, -1, 1 };
        static List<int> list = new List<int>();
        static void BFS(int x, int y)
        {
            int count = 0;
            q.Enqueue((x, y));
            while (q.Count > 0)
            {
                count++;
                var deq = q.Dequeue();
                int deqx = deq.Item1;
                int deqy = deq.Item2;
                visited[deqx, deqy] = true;
                for (int i = 0; i < 4; i++)
                {
                    deqx = deq.Item1 + dx[i];
                    deqy = deq.Item2 + dy[i];
                    if (deqx < 0 || deqy < 0 || deqx >= N || deqy >= N) continue;
                    if (map[deqx, deqy] == 1 && visited[deqx, deqy] == false)
                        q.Enqueue((deqx, deqy));
                    visited[deqx, deqy] = true;
                }
            }
            list.Add(count);
        }
        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            //입력
            N = int.Parse(sr.ReadLine());
            for(int i = 0; i < N; i++)
            {
                string str = sr.ReadLine();
                for (int j = 0; j < N; j++) map[i, j] = (int)str[j] - 48;   //아스키코드
            }

            //BFS
            for(int i = 0; i < N; i++)
            {
                for(int j = 0; j < N; j++)
                {
                    if (map[i, j] == 1 && visited[i, j] == false)
                        BFS(i, j);
                }
            }
            sb.Append(list.Count + "\n");
            list.Sort();
            foreach (var count in list) sb.Append(count + "\n");
            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90