#include <iostream> #include <algorithm> #include <queue> #define MAX 100 using namespace std; int dy[] = {1,-1,0,0}; int dx[] = {0,0,1,-1}; int map[MAX][MAX]; int visited[MAX][MAX]; int n,m; queue<pair<int, int> > q; bool isInside(int y, int x) { return (y >= 0 && x >= 0 && y < n && x < m); } int bfs(int startY, int startX) { int nowY = startY; int nowX = startX; q.push({nowY, nowX}); visited[nowY][nowX] = 1; while(!q.empty()) { nowY = q.front().first; nowX = q.front().second; q.pop(); if(!isInside(nowY,nowX)) continue; for(int i=0;i<4;i++) { int nextY = nowY + dy[i]; int nextX = nowX + dx[i]; if(isInside(nextY,nextX) && !visited[nextY][nextX] && map[nextY][nextX]) { visited[nextY][nextX] = visited[nowY][nowX] + 1; q.push({nextY, nextX}); } } } return visited[n-1][m-1]; } int main() { scanf("%d %d",&n,&m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%1d",&map[i][j]); printf("%d",bfs(0,0)); }

BFS를 이용한 풀이입니다.

+ Recent posts