CodeLabs

[백준 / C#] 7576 : 토마토 본문

백준/5000~

[백준 / C#] 7576 : 토마토

무오_ 2023. 6. 30. 18:29
using System;
using System.Collections.Generic;
using System.Linq;

namespace _7576
{
    struct Tomato
    {
        public int y, x;

        public Tomato(int i, int j)
        {
            y = i;
            x = j;
        }
    }
    class Program
    {
        static int n, m, result = 0;
        static int[] dx = { 1, 0, -1, 0 }, dy = { 0, 1, 0, -1 }; // 우 하 좌 상
        static int[,] box = new int[1001, 1001];
        static Queue<Tomato> q = new Queue<Tomato>();
        static void BFS()
        {
            while (!q.Count.Equals(0))
            {
                int y = q.Peek().y;
                int x = q.Peek().x;
                q.Dequeue();
                for(int i=0; i<4; i++)
                {
                    int newY = y + dy[i];
                    int newX = x + dx[i];
                    if (0 <= newX && newX < m && 0<=newY && newY<n && box[newY,newX] == 0)
                    {
                        box[newY, newX] = box[y, x] + 1;
                        q.Enqueue(new Tomato(newY, newX));
                    }
                }
            }
        }
        static void Soulution()
        {
            BFS();
            for(int i=0; i<n; i++)
            {
                for(int j=0; j<m; j++)
                {
                    if(box[i,j] ==0)
                    {
                        Console.WriteLine("-1");
                        return;
                    }
                    if (result < box[i, j])
                        result = box[i, j];
                }
            }
            Console.WriteLine(result - 1);
        }
        static void Input()
        {
            int[] M_N = Console.ReadLine().Split().Select(int.Parse).ToArray();
            m = M_N[0]; n = M_N[1];
            for (int i = 0; i < n; i++)
            {
                int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
                for (int j = 0; j < m; j++)
                {
                    box[i, j] = input[j];
                    if (box[i, j] == 1)
                        q.Enqueue(new Tomato(i, j));
                }
            }
        }
        static void Solve()
        {
            Input();
            Soulution();
        }
        static void Main(string[] args)
        {
            Solve();
        }
    }
}

'백준 > 5000~' 카테고리의 다른 글

[백준 / C#] 7569 : 토마토  (0) 2023.06.28
[백준 / C#] 9019 : DLSR  (0) 2023.06.24