#include <bits/stdc++.h>
using namespace std;
int m, n;
char check[101][101];
int visted[101][101];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,-1,0,1 };
queue<pair<int,int>> qu;
void bfs(int x,int y) {
visted[x][y] = 1;
while (!qu.empty()) {
int x = qu.front().first;
int y = qu.front().second;
qu.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<0 || nx>n-1|| ny<0 || ny>m-1) continue;
if (check[nx][ny]=='1'&&visted[nx][ny]==0) {
visted[nx][ny] = visted[x][y]+1;
qu.push(make_pair(nx, ny));
}
}
}
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> check[i][j];
}
}
qu.push(make_pair(0, 0));
bfs(0,0);
cout << visted[n - 1][m - 1];
}
BFS의 개념을 알고 있다면 쉽게 풀 수 있는 문제이다.
visted의 이동경로를 출력해주면, 저런식으로 탐색하는것을 알 수 있다.
디버깅할때도 육안으로 쉽게 볼 수 있습니다.!
'Algorithm > graph' 카테고리의 다른 글
[백준] 알고리즘 2644번 - 촌수계산 문제 (0) | 2021.01.31 |
---|---|
[백준] 알고리즘 4963번 - 섬의 개수 문제 (0) | 2021.01.29 |
[백준] 알고리즘 7576번 - 토마토 문제 (0) | 2021.01.27 |
[백준] 알고리즘 2667번 - 단지번호붙이기 문제 (0) | 2021.01.26 |
[백준] 알고리즘 9466번 - 텀 프로젝트 문제 (0) | 2021.01.24 |