C# 백준 2667번 문제 단지번호붙이기
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]);
}
}
}
}