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

seio·2022년 10월 30일
0

coding study

목록 보기
10/12
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
int search[5] =  {0, 1, 0, -1, 0};

int solution(vector<vector<int> > maps)
{
    int answer = -1;
    
    int rows = maps.size();
    int cols = rows>0 ? maps[0].size(): 0;
    
    if(rows==0||cols==0)
        return -1;
    
    queue<pair<int,int>> pos; // y,x
    
    pos.push(make_pair(0,0));
    
    while(!pos.empty()){
        
        pair<int,int> po = pos.front();
        pos.pop();
        int y = po.first;
        int x = po.second;
        int val = maps[y][x];
                
            if(y==rows-1 &&x==cols-1)
                answer = val;
        
        for(int i=0;i<4;i++){
            int ny = y + search[i];
            int nx = x + search[i+1];
            
           if (ny < 0 || ny >= rows || nx < 0 || nx >= cols)
                continue;                        
            
            if(maps[ny][nx]==0)
                continue;
            
            if(maps[ny][nx]>1)
                continue;
                 
            if(maps[ny][nx]==1){
                maps[ny][nx] = val+1;
                pos.push(make_pair(ny,nx));
            }

        }
    }
    



    return answer;
}
profile
personal study area

0개의 댓글