[프로그래머스] 미로 탈출(C++)

2025. 4. 17. 16:10·개발/알고리즘
728x90

문제 링크

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

코드 구현

#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;

struct Point
{
    int y, x;
    int score;

    bool operator==(const Point& other) const
    {
        return y == other.y && x == other.x;
    }

    Point operator+(const Point& other) const
    {
        return Point(y + other.y, x + other.x);
    }

    Point(int _y, int _x, int _score = 0)
        : y(_y)
        , x(_x)
        , score(_score) 
    {}
};

bool IsValid(const Point& _point, const int& _height, const int& _width)
{
    return (_point.y >= 0 && _point.y < _height && _point.x >= 0 && _point.x < _width);
}

vector<Point> direction = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };

int height, width;

int bfs(char _start, char _end, vector<string>& maps)
{
    vector<vector<bool>> visited(height, vector<bool>(width, false));
    queue<Point> q;

    Point start(0, 0), end(0, 0);

    // 시작 - 끝 지점 좌표로 변환
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            if (maps[i][j] == _start) start = { i, j };
            if (maps[i][j] == _end) end = { i, j };
        }
    }

    q.push(start);

    while (!q.empty())
    {
        Point now = q.front();
        q.pop();

        if (now == end)
        {
            return now.score;
        }

        // 상하좌우 갈 수 있는 타일 체크
        for (int i = 0; i < 4; i++)
        {
            Point next = now + direction[i];

            // 벽이 아니고 방문한 적 없는 타일이면
            if (IsValid(next, height, width) && maps[next.y][next.x] != 'X' && !visited[next.y][next.x])
            {
                // 큐에 삽입 + 방문 체크
                next.score += now.score + 1;
                q.push(next);
                visited[next.y][next.x] = true;
            }
        }
    }

    return 0;
}


int solution(vector<string> maps)
{
    int answer = 0;

    height = maps.size();
    width = maps[0].length();

    int distanceSToL = bfs('S', 'L', maps);

    int distanceLToE = bfs('L', 'E', maps);

    if (distanceSToL == 0 || distanceLToE == 0) return -1;

    return distanceSToL + distanceLToE;
}

 

 

해결 방법

최단 거리 찾기 이므로 BFS 알고리즘을 사용하였고, 맵의 좌표를 담을 Point 구조체를 만들었다.

레버를 반드시 당겨야 목적지까지 갈 수 있으므로 '시작점 - 레버' 까지의 최소 거리와 '레버 - 목적지' 까지의 걸린 시간을 더한 값이 답이 된다. 둘 중 하나라도 시간이 0이 나오면 갈 수 없다는 의미이므로 -1을 반환한다.

'개발 > 알고리즘' 카테고리의 다른 글

[프로그래머스] 타겟 넘버(C++)  (1) 2025.04.19
[백준] 2606번: 바이러스(C++)  (2) 2025.04.18
[프로그래머스] 게임 맵 최단거리(C++)  (1) 2025.04.15
BFS 구현(C++)  (0) 2025.04.14
DFS 구현 (C++)  (0) 2025.04.14
'개발/알고리즘' 카테고리의 다른 글
  • [프로그래머스] 타겟 넘버(C++)
  • [백준] 2606번: 바이러스(C++)
  • [프로그래머스] 게임 맵 최단거리(C++)
  • BFS 구현(C++)
Majangnan
Majangnan
  • Majangnan
    개발 모코코
    Majangnan
  • 전체
    오늘
    어제
    • 분류 전체보기 (68) N
      • 개발 (67) N
        • C# (10)
        • SQL (3)
        • Unity (8)
        • Unreal (10)
        • C++ (3)
        • Server (1)
        • DX11 (8)
        • 알고리즘 (23) N
  • 블로그 메뉴

    • 홈
    • 방명록
    • 깃허브
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    dx3d
    코딩테스트
    Mecanim
    슈팅게임
    3dlight
    프로그래머스
    c++
    언리얼
    DirectX11
    blueprint
    C#
    DX11
    sql
    블루프린트
    알고리즘
    백준
    UnReal
    Unity
    상속
    MAC
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Majangnan
[프로그래머스] 미로 탈출(C++)
상단으로

티스토리툴바