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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _230210_1
{
    class Program
    {
        static int n, m;
        static int[,] check = new int[101, 101]; // 시작점 부터의 거리
        static char[,] map = new char[101, 101]; 
        static int[,] visited = new int[101, 101];
        static int[] dx = { 1, 0, -1, 0 };
        static int[] dy = { 0, 1, 0, -1 };

        static void Main(string[] args)
        {
            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];

            for(int i = 0; i < n; i++)
            {
                string str = sr.ReadLine();
                for(int j = 0; j < m; j++)
                {
                    map[i, j] = str[j];
                }
            }

            BFS(0, 0);
            sw.WriteLine(check[n - 1, m - 1] + 1);

            sr.Close();
            sw.Close();
        }

        static void BFS(int x, int y)
        {
            visited[x, y] = 1; // 방문표시

            Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>(); ; // 큐 생성
            Tuple<int, int> tuple = new Tuple<int, int>(x, y);
            q.Enqueue(tuple); // 시작점 넣기

            while (q.Count > 0) // 큐에 데이터가 없을때까지
            {
                x = q.Peek().Item1;
                y = q.Peek().Item2;

                q.Dequeue(); // 큐 맨 앞 데이터 제거

                for (int i = 0; i < 4; i++)
                {
                    int nextX = x + dx[i];
                    int nextY = y + dy[i];

                    if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m) // 미로의 범위
                    {
                        // 길이 존재하고 이전에 방문했던적이 없는 경우
                        if (map[nextX, nextY] == '1' && visited[nextX, nextY] == 0)
                        {
                            check[nextX, nextY] = check[x, y] + 1;
                            visited[nextX, nextY] = 1;
                            Tuple<int, int> tuple2 = new Tuple<int, int>(nextX, nextY);
                            q.Enqueue(tuple2); // 큐에 데이터 밀어넣기
                        }
                    }
                }
            }
        }
    }
}

 

아래 블로그 참조하여 작성하였는데 아직 이해가 안돼서 주기적으로 보면서 공부해야겠다.

https://cocoon1787.tistory.com/115

'Algorithm > BOJ' 카테고리의 다른 글

C#) [BOJ] 1254 팰린드롬 만들기 ★  (0) 2023.02.14
C#) [BOJ] 21921 블로그 ★  (0) 2023.02.13
C#) [BOJ] 2108 통계학 ★  (0) 2023.02.09
C#) [BOJ] [BOJ] 1297 TV 크기  (0) 2023.02.08
C#)[BOJ] 1764 듣보잡 ★  (0) 2023.02.06

+ Recent posts