프로그래머스의 게임 맵 최단거리(Lv4) 문제이다.


[ 문제풀이 ]

본인은 이 문제를 너비우선탐색(BFS)를 통해서 접근해 보았다.

Queue에서는 (x, y) 좌표와, 현재까지 움직인 횟수, 총 3개의 변수를 관리해 주었고, 2차원 bool형 배열을 하나 선언해서 중복된 방문을 하지 않도록 구현하였다.


[ 소스코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<vector>
#include<queue>
using namespace std;
 
bool Visit[100][100];
 
int dx[] = { 001-1 };
int dy[] = { 1-100 };
 
int solution(vector<vector<int> > maps)
{
    int N = maps.size();
    int M = maps[0].size();
    queue<pair<pair<intint>int>> Q;
    Q.push(make_pair(make_pair(00), 1));    
    Visit[0][0= true;
    
    while(Q.empty() == 0)
    {
        int x = Q.front().first.first;
        int y = Q.front().first.second;
        int Cnt = Q.front().second;
        Q.pop();
        
        if(x == N - 1 && y == M - 1return Cnt;
        
        for(int i = 0;  i < 4; i++)
        {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx >= 0 && ny >= 0 && nx < N && ny < M)
            {
                if(Visit[nx][ny] == false && maps[nx][ny] == 1)
                {
                    Visit[nx][ny] = true;
                    Q.push(make_pair(make_pair(nx, ny), Cnt + 1));
                }
            }
        }
    }
    return -1;
}
cs


+ Recent posts