코딩공부/프로그래머스

※[프로그래머스]Lv.2 미로 탈출 C#

usingsystem 2023. 6. 27. 15:41
728x90

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

 

프로그래머스

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

programmers.co.kr

 

소스코드

using System;
using System.Collections.Generic;
public class Solution
{
    static Pos _end;
    public int solution(string[] maps)
    {
        int answerL = 0;
        int answerE = 0;

        Pos startPos = null;
        for (int i = 0; i < maps.Length; i++)
        {
            int idx = maps[i].IndexOf('S');
            if (idx != -1)
            {
                startPos = new Pos(i, idx);
                break;
            }
        }

        answerL = BFS(maps, 'L', startPos);
        if (answerL == -1)
            return -1;

        answerE = BFS(maps, 'E', _end);
        if (answerE == -1)
            return -1;

        return answerL + answerE;
    }
    public static int BFS(string[] maps, Pos start, char target)
    {
        if (start == null)
            return -1;

        //Up = 0, Left = 1, Down = 2, Right = 3
        int[] deltaY = new int[] { -1, 0, 1, 0 };
        int[] deltaX = new int[] { 0, -1, 0, 1 };

        int[,] dist = new int[maps.Length, maps[0].Length];//시작점에서 부터 지점까지의 거리

        Queue<Pos> q = new Queue<Pos>();
        q.Enqueue(start);

        while (q.Count > 0)
        {
            Pos now = q.Dequeue();

            if (maps[now.Y][now.X] == target)
            {
                _end = now;
                return dist[now.Y, now.X];
            }

            for (int i = 0; i < 4; i++)
            {
                int nextY = now.Y + deltaY[i];
                int nextX = now.X + deltaX[i];

                if (nextY >= maps.Length || nextY < 0)
                    continue;
                if (nextX >= maps[0].Length || nextX < 0)
                    continue;

                if (maps[nextY][nextX] == 'X')
                    continue;
                if (dist[nextY, nextX] != 0)//경유한지점
                    continue;

                q.Enqueue(new Pos(nextY, nextX));

                dist[nextY, nextX] = dist[now.Y, now.X] + 1;
            }
        }
        return -1;
    }
}

public class Pos
{
    public int Y;
    public int X;

    public Pos(int y, int x)
    {
        Y = y;
        X = x;
    }
}
728x90