코딩공부/프로그래머스

[프로그래머스]Lv.2 게임 맵 최단거리 C#(BFS)

usingsystem 2023. 8. 2. 15:20
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/1844

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

소스코드

using System;
using System.Collections.Generic;

class Solution
{
    int maxY = 0;
    int maxX = 0;
    public int solution(int[,] maps)
    {
        maxX = maps.GetLength(1);
        maxY = maps.GetLength(0);
        Bfs(maps);

        return maps[maxY - 1, maxX - 1] == 1 ? -1 : maps[maxY - 1, maxX - 1];
    }
    void Bfs(int[,] maps)
    {
        Queue<(int, int)> queue = new Queue<(int, int)>();
        int[] dirY = { -1, 1, 0, 0 };//상하좌우 
        int[] dirX = { 0, 0, -1, 1 };

        bool[,] visit = new bool[maxY, maxX];
        visit[0, 0] = true;
        queue.Enqueue((0, 0));

        while (queue.Count > 0)
        {
            (int curY, int curX) = queue.Dequeue();

            for (int i = 0; i < 4; i++)
            {
                int nextY = curY + dirY[i];
                int nextX = curX + dirX[i];

                if (nextX < 0 || nextX >= maxX || nextY < 0 || nextY >= maxY)
                    continue;

                if (maps[nextY, nextX] == 0)
                    continue;

                if (visit[nextY, nextX] == true)
                    continue;

                if (maps[nextY, nextX] == 1)
                {
                    maps[nextY, nextX] = maps[curY, curX] + 1;
                    queue.Enqueue((nextY, nextX));
                    visit[nextY, nextX] = true;
                }
            }
        }
    }
}
728x90