본문으로 바로가기

#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의 이동경로를 출력해주면, 저런식으로 탐색하는것을 알 수 있다.

디버깅할때도 육안으로 쉽게 볼 수 있습니다.!