#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
int n,m;
string board[1003];
int dist[1003][1003][2];
int bfs(){
memset(dist,-1,sizeof(dist));
dist[0][0][0]=0;
dist[0][0][1]=0;
queue<tuple<int,int,int>> q;
q.push({0,0,0});
while(!q.empty()) {
int x,y,broken;
tie(x,y,broken)=q.front();q.pop();
if(x==n-1 && y==m-1) return dist[x][y][broken]+1;
int nxtdist=dist[x][y][broken]+1;
for(int idx=0; idx<4; idx++) {
int nx=x+dx[idx];
int ny=y+dy[idx];
if(nx<0 || nx>=n || ny<0 || ny>=m) continue;
//길이고 방문 안됨
if(dist[nx][ny][broken]<0 && board[nx][ny]=='0') {
q.push({nx,ny,broken});
dist[nx][ny][broken]=nxtdist;
}
//길이 아닌데 벽을 안부섰음 방문 안됨
if(board[nx][ny]=='1' && broken==0 && dist[nx][ny][broken]<0 ) {
q.push({nx,ny,1});
dist[nx][ny][1]=nxtdist;
}
}
}
return -1;
}
int main() {
cin.tie(0);
cin >> n >> m;
for(int i=0; i<n; i++) {
cin >> board[i];
}
cout << bfs();
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: