[2667] c# 풀이 단지번호 붙이기 - BFS
2019. 10. 12. 00:44ㆍIT#개발/알고리즘
BFS (깊이 우선 탐색) 방법으로 풀이했습니다.
C#을 이용한 풀이입니다.
[ 문제 풀이 ]
using System;
using System.Collections.Generic;
using System.Linq;
namespace Programs
{
public class _2667BFS
{
private static int[,] array;
private static int count = 1;
private static Dictionary<int, int> sorted;
private static int[,] dir = new int[,] { { -1, 0},
{ 1, 0},
{ 0, -1},
{ 0, 1} };
private static bool[,] visit;
public static void Main()
{
var r = int.Parse(Console.ReadLine());
array = new int[r, r];
visit = new bool[r, r];
for (int i = 0; i < r; i++)
{
var re = Console.ReadLine();
for (int j = 0; j < re.Length; j++)
{
array[i, j] = int.Parse(re[j].ToString());
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
if (array[i, j] == 1)
{
Bfs(i, j, ++count);
}
}
}
sorted = new Dictionary<int, int>();
foreach (var item in array)
{
if (item == 0) continue;
if (!sorted.ContainsKey(item))
sorted.Add(item, 1);
else
sorted[item] += 1;
}
Console.WriteLine(sorted.Count());
var so = sorted.Values.ToList();
so.Sort();
so.ForEach(x => { Console.WriteLine(x); });
}
private static void Bfs(int i, int j, int v)
{
var queue = new Queue<Node>();
visit[i, j] = true;
array[i, j] = v;
queue.Enqueue(new Node(i, j));
while (queue.Count() != 0)
{
var node = queue.Dequeue();
var row = node.y;
var col = node.x;
for (int k = 0; k < 4; k++)
{
var dy = row + dir[k, 0];
var dx = col + dir[k, 1];
if (IsCheck(dy, dx) && !visit[dy, dx] && array[dy, dx] != 0)
{
visit[dy, dx] = true;
array[dy, dx] = count;
queue.Enqueue(new Node(dy, dx));
}
}
}
}
private static bool IsCheck(int dy, int dx)
{
return (dy >= 0 && dy < array.GetLength(0) &&
(dx >= 0 && dx < array.GetLength(0)));
}
public class Node
{
public int y;
public int x;
public Node(int dy, int dx)
{
y = dy;
x = dx;
}
}
}
}
'IT#개발 > 알고리즘' 카테고리의 다른 글
[2748] C# 풀이 피보나치 수 2 (0) | 2019.11.07 |
---|---|
c# 기수정렬 (radix sort) (0) | 2019.10.16 |
[2667] c# 풀이 단지번호 붙이기 - DFS (0) | 2019.10.04 |