문제설명
https://school.programmers.co.kr/learn/courses/30/lessons/1844
코드
#include<vector>
#include<queue>
#include<iostream>
using namespace std;
int visited[101][101]={};
int dx[4]= {-1,1,0,0};
int dy[4]= {0,0,-1,1};
int solution(vector<vector<int> > maps)
{
int answer = 0;
queue<pair<int,int>> q;
q.push({0,0});
visited[0][0] = 1;
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int i=0; i< 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0 && ny>=0 && nx<maps.size() && ny<maps[0].size()){//범위를 벗어나지 않도록 제한
if(visited[nx][ny]==0 && maps[nx][ny]==1){//방문한적 없으며 이동할 수 있는 곳이면 이동
q.push({nx, ny});
visited[nx][ny] = visited[x][y]+1;
}
}
}
}
if(visited[maps.size()-1][maps[0].size()-1]==0)// 도달하지 못하는 경우
return -1;
answer = visited[maps.size()-1][maps[0].size()-1];
return answer;
}
'Algorithm' 카테고리의 다른 글
[프로그래머스] 음양더하기 (0) | 2023.03.05 |
---|---|
[프로그래머스] 뒤에 있는 큰 수 찾기 (0) | 2023.03.05 |
[프로그래머스] 가장 가까운 같은 글자 (0) | 2023.02.24 |
[프로그래머스] 크기가 작은 부분 문자열 (0) | 2023.02.22 |
[프로그래머스] 귤 고르기 (0) | 2023.02.22 |