(C#) 백준 7569 : 토마토 (BFS)

2024. 2. 18. 02:51문제 풀기

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

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net

using System.Text;
using System.Linq;

int[] sizes = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
int[,,] box = new int[sizes[0], sizes[1], sizes[2]];
int needChangeTomatoCount = 0;

Queue<Cell> queue = new Queue<Cell>();

for (int i = 0; i < sizes[2]; i++)
{
    for (int j = 0; j < sizes[1]; j++)
    {
        string[] inputs = Console.ReadLine().Split(' ');

        for (int k = 0; k < sizes[0]; k++)
        {
            int value = int.Parse(inputs[k]);
            box[k, j, i] = value;
            if (value == 0)
            {
                needChangeTomatoCount++;
            }
            else if (value == 1)
            {
                queue.Enqueue(new Cell(i, j, k, 0));
            }
        }
    }
}

NextDay(out int changedCount, out int day);
needChangeTomatoCount -= changedCount;

if (needChangeTomatoCount == 0)
{
    Console.WriteLine(day);
}
else
{
    Console.WriteLine(-1);
}

void NextDay(out int changedCount, out int maxDay)
{
    changedCount = 0;
    maxDay = 0;

    while (queue.Count > 0)
    {
        var cell = queue.Dequeue();
        int i = cell.i;
        int j = cell.j;
        int k = cell.k;
        int day = cell.day + 1;

        TryChange(i + 1, j, k, day, ref changedCount, ref maxDay);
        TryChange(i - 1, j, k, day, ref changedCount, ref maxDay);
        TryChange(i, j + 1, k, day, ref changedCount, ref maxDay);
        TryChange(i, j - 1, k, day, ref changedCount, ref maxDay);
        TryChange(i, j, k + 1, day, ref changedCount, ref maxDay);
        TryChange(i, j, k - 1, day, ref changedCount, ref maxDay);
    }

    void TryChange(int i, int j, int k, int day, ref int changedCount, ref int maxDay)
    {
        if (!CanChange(i, j, k)) return;
        changedCount++;
        box[k, j, i] = 1;
        maxDay = maxDay > day ? maxDay : day;
        queue.Enqueue(new Cell(i, j, k, day));
    }

    bool CanChange(int i, int j, int k)
    {
        // out of array
        if (i < 0 || j < 0 || k < 0) return false;
        if (i >= sizes[2] || j >= sizes[1] || k >= sizes[0]) return false;
        // need change
        return box[k, j, i] == 0;
    }
}

struct Cell
{
    public int i, j, k, day;

    public Cell(int i, int j, int k, int day)
    {
        this.i = i;
        this.j = j;
        this.k = k;
        this.day = day;
    }
}

 

간단한 BFS 알고리즘입니다.

근데 오랜만에 해서 감 잡느라 좀 걸렸네요.

'문제 풀기' 카테고리의 다른 글

(C#) 백준 14502번 : 연구소 (BFS)  (0) 2024.02.18
(C#) 백준 9663번 N-Queen (퀸 배치 문제)  (0) 2024.02.18
(c#) 백준 2447 별찍기  (0) 2024.02.18