#include <iostream>
#include <string>
#include <queue>
#include <algorithm>

using namespace std;
#define X first
#define Y second

string borad[102];
//bool vis[102][102];
int dist[102][102];

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n,m;
    cin >> n >> m;

    for(int i=0; i<n; i++) {
        cin >> borad[i];
    }

    for(int i=0; i<n; i++) fill(dist[i],dist[i]+m,-1);
    queue<pair<int,int>> q;
    q.push({0,0});
    dist[0][0]=0;

    while(!q.empty()) {
        pair<int,int> cur=q.front();
        int cur_dist=dist[cur.X][cur.Y];
        q.pop();
        for(int i=0; i<4; i++) {
            int nx=cur.X+dx[i];
            int ny=cur.Y+dy[i];
            if(nx<0 || nx>=n || ny<0 || ny>=m) continue;
            if(dist[nx][ny]>=0 || borad[nx][ny]!='1') continue;

            dist[nx][ny]=cur_dist+1;
            q.push({nx,ny});
        }
    }
    cout << dist[n-1][m-1]+1;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: