오늘의 알고리즘

[C++]찾아라 프로그래밍 마에스터게임 맵 최단거리(프로그래머스 2레벨)

하늘하늘 . 2022. 3. 8. 20:32
#include<vector>
#include<queue>
 
using namespace std;
 
bool visit[101][101] = { false };
 
int solution(vector<vector<int>> maps)
{
    // {{ X, Y}, Count }
    queue<pair<pair<int, int>, int>> que = {};
    que.push({ { 0,0 },1 });
 
    while (!que.empty())
    {
        pair<pair<int, int>, int> pairInt = que.front();
        que.pop();
 
        int iX = pairInt.first.first;
        int iY = pairInt.first.second;
 
        // 방문을 안했다면 true로 변경 후 진입
        if (!visit[iX][iY])
            visit[iX][iY] = true;
 
        // 방문을 했다면 다음으로 넘어가기
        else
            continue;
 
        // 마지막으로 진입했다면
        if (iX == maps.size() - 1 && iY == maps[0].size() - 1)
            return pairInt.second;
 
        // X축을 넘지 않고, 갈 수 있는 길이라면
        if (iX + 1 < maps.size())
            if (maps[iX + 1][iY])
                que.push({ { iX + 1,iY },pairInt.second + 1 });
 
        // Y축을 넘지 않고, 갈 수 있는 길이라면
        if (iY + 1 < maps[0].size())
            if (maps[iX][iY + 1])
                que.push({ { iX,iY + 1 }, pairInt.second + 1 });
 
        // 0보다 크고, 갈 수 있는 길이라면
        if (iX - 1 >= 0)
            if (maps[iX - 1][iY])
                que.push({ { iX - 1,iY },pairInt.second + 1 });
 
        // 0보다 크고, 갈 수 있는 길이라면
        if (iY - 1 >= 0)
            if (maps[iX][iY - 1])
                que.push({ { iX,iY - 1 },pairInt.second + 1 });
    }
 
    // 길이 막혔다면 
    return -1;
}

처음엔 DFS로 완전탐색을 하려했는데 바로 시간초과뜨길래 BFS로 선회... 길을 못찾을 경우 생각했는데 그래도 visit을 측정하고 계속 가니까 BFS가 더 빠르네