본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 21736 헌내기는 친구가 필요해

by 왹져박사 2023. 10. 19.
728x90

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

 

21736번: 헌내기는 친구가 필요해

2020년에 입학한 헌내기 도연이가 있다. 도연이는 비대면 수업 때문에 학교에 가지 못해 학교에 아는 친구가 없었다. 드디어 대면 수업을 하게 된 도연이는 어서 캠퍼스 내의 사람들과 친해지고

www.acmicpc.net

BFS로 풀었다. 

비교적 간단한 문제였다. 

using System;
using System.IO;

namespace B21736
{
    class Program
    {
        static int N, M;
        static int count = 0;
        static int[,] map = new int[601, 601];
        static bool[,] visited = new bool[601, 601];
        static Queue<(int, int)> q = new Queue<(int, int)>();
        static int[] dx = { -1, 1, 0, 0 };
        static int[] dy = { 0, 0, -1, 1 };
        static bool isDone = false;
        static void BFS()
        {
            while (q.Count > 0)
            {
                var deq = q.Dequeue();
                int deqx = deq.Item1;
                int deqy = deq.Item2;
                visited[deqx, deqy] = true;
                //4방향 탐색
                for (int i = 0; i < 4; i++)
                {
                    deqx = deq.Item1 + dx[i];
                    deqy = deq.Item2 + dy[i];
                    //맵으 넘어가거나 방문리스트에 있다면 continue
                    if (deqx < 0 || deqy < 0 || deqx >= N || deqy >= M || visited[deqx, deqy] == true)
                        continue;
                    visited[deqx, deqy] = true;
                    //X면 continue
                    if (map[deqx, deqy] == 'X') continue;
                    else
                    {
                        //아니면 Queue에 넣기
                        q.Enqueue((deqx, deqy));
                        //P면 사람 수 더해주기
                        if (map[deqx, deqy] == 'P') count++;
                    }
                }
            }
        }
        static void Main()
        {
            StreamReader sr = new StreamReader((Console.OpenStandardInput()));
            StreamWriter sw = new StreamWriter((Console.OpenStandardOutput()));
            int[] nm = Array.ConvertAll(sr.ReadLine().Split(' '), int.Parse);
            N = nm[0];
            M = nm[1];
            int x = 0;
            int y = 0;
            for (int i = 0; i < N; i++)
            {
                string str = sr.ReadLine();
                for (int j = 0; j < M; j++)
                {
                    map[i, j] = str[j];
                    if (str[j] == 'I')
                    {
                        x = i;
                        y = j;
                    }
                }
            }
            q.Enqueue((x, y));
            BFS();
            if (count == 0) sw.Write("TT");
            else sw.Write(count);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90

'알고리즘 > 백준 BOJ' 카테고리의 다른 글

[ BOJ/C# ] 1966 프린터 큐  (0) 2023.10.21
[ BOJ/C# ] 14940 쉬운 최단거리  (0) 2023.10.19
[ BOJ/C# ] 2231 분해합  (0) 2023.10.18
[ BOJ/C# ] 2292 벌집  (0) 2023.10.17
[ BOJ/C# ] 2609 최대공약수와 최소공배수  (0) 2023.10.16