모든 일상

C# 백준 2667번 문제 단지번호붙이기 본문

코딩 공부/C#

C# 백준 2667번 문제 단지번호붙이기

통통푸린 2022. 8. 10. 11:58
728x90
반응형

using System;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApp3
{
    public class Program
    {
        static void Main(string[] args)
        {
            int size = int.Parse(Console.ReadLine());
            int[,] value = new int[size, size];
            int[,] visit = new int[size, size];
            int[] dx = new int[4] { 1, 0, -1, 0 };
            int[] dy = new int[4] { 0, 1, 0, -1 };
            Queue<(int, int)> q = new Queue<(int, int)>(); // X,Y 축 위치 저장
            Queue<int> result = new Queue<int>();  // 넓이 결과 저장
            int num = 0;
            for (int i = 0; i < size; i++)
            {
                string s = Console.ReadLine();
                for (int j = 0; j < size; j++)
                {
                    value[i, j] = int.Parse(s.Substring(j, 1));
                }
            }

            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    if (value[i, j] == 1 && visit[i, j] == 0)
                    {
                        int cnt = 0;
                        cnt++;
                        num++;
                        q.Enqueue((i, j));

                        visit[i, j] = 1;

                        while (q.Count != 0)
                        {
                            var buff = q.Dequeue();
                            int check_x = buff.Item2;
                            int check_y = buff.Item1;

                            for (int z = 0; z < 4; z++)
                            {
                                int x = check_x + dx[z];
                                int y = check_y + dy[z];

                                if (x < 0 || x >= size || y < 0 || y >= size) continue; // 배열 범위 밖의 값 Pass
                                if (value[y, x] != 1 || visit[y, x] == 1) continue;         // 배열의 값이 0이거나 방문한 곳은 Pass
 
                                cnt++;
                                visit[y, x] = 1;
                                q.Enqueue((y, x));

                            }
                        }
                        result.Enqueue(cnt);  // 단지 넓이 값  저장
                    }
                }
            }
            int[] arr = new int[result.Count];
            int arr_cnt = 0;
            while (result.Count != 0)
            {
                arr[arr_cnt] = result.Dequeue();
                arr_cnt++;
            }          
            Console.WriteLine(num);
            Array.Sort(arr);
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine(arr[i]);
            }
        }
    }
}

728x90
반응형

'코딩 공부 > C#' 카테고리의 다른 글

C# 2587번 문제 대표값2  (0) 2023.01.10
C# 2566번 문제 최댓값  (0) 2023.01.09
C# 백준 2583번 문제 영역 구하기  (0) 2022.08.10
C# 백준 7562번 문제 나이트의 이동  (0) 2022.08.05
C# 백준 1696번 문제 숨바꼭질  (0) 2022.08.05