bfs : 프로그래머스 - 게임맵 최단거리

phoenixKim·2021년 9월 8일
0

주의할점.

1. 축을 어떻게 지정할지

  • x값은 second값이고, y값은 first값이다.
    그리고 x값은 가로의 총길이를 나타내고,
    y값은 세로를 나타낸다.

  • vector<vector>v에서
    v.size()는 세로의 길이고, v[0].size()는 가로의 길이이므로
    second는 v[0].size()와 매칭이 되어야 하고,
    first는 v.size()와 매칭이 되어야한다.

2. [Y][X]라고 통일했으면 집중해서 인덱스에 올바른 X와 Y를 집어넣자.

소스코드

#include<vector>
#include <queue>
using namespace std;

int solution(vector<vector<int> > maps)
{
    int answer = 0;
    
    int n = maps.size();    //세로
    int m = maps[0].size(); //가로
    
    //상하좌우
    int dx[4] = {0,0,-1,1};
    int dy[4] = {-1,1,0,0};
    
    //(0,0) (0,1) (0,2) (0,3) (0,4)
    //(1,0) (1,1) (1,2) (1,3) (1,4)
    //(2,0) (2,1) (2,2) (2,3) (2,4)
    
    
    queue<pair<int,int>>q;    
    q.push({0,0});
    
    while(!q.empty())
    {
        int curX = q.front().second;
        int curY = q.front().first;
        q.pop();
        
        for(int i = 0; i < 4; i++)
        {
            int nextX = curX + dx[i];
            int nextY = curY + dy[i];
            
            //이 부분이 문제다...X는 second를 나타내고, x는 가로다.
            //Y는 first를 나타내는데,,, y는 세로축을 나타낸다.
            if(nextX < 0 || nextX >= m 
              || nextY < 0 || nextY >= n)
                continue;
            
            if(maps[nextY][nextX] == 1)
            {
                q.push({nextY, nextX});
                maps[nextY][nextX] += maps[curY][curX];
            }        
        }     
    }
    
    if(maps[n - 1][m - 1] <= 1)
        answer = -1;
    else 
        answer = maps[n - 1][m - 1];
    
    
    return answer;
}
profile
🔥🔥🔥

0개의 댓글

관련 채용 정보