#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;
string board[1005];
int dist[1005][1005][11];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int escape=0;
    int k,n,m;
    cin >> n >> m >> k;
    for(int i=0 ;i<n; i++) {
        cin >> board[i];
    }
    memset(dist,-1,sizeof(dist));
    queue<tuple<int,int,int>> q;
    q.push({0,0,0});
    dist[0][0][0]=1;
    while(!q.empty()) {
        int x,y,broken;
        tie(x,y,broken)=q.front(); q.pop();
        if(x== n-1 && y== m-1) {
                cout << dist[x][y][broken];
                escape =1;
                return 0;
            }
        for(int idx=0; idx<4; idx++) {
            int nx=x+dx[idx];
            int ny=y+dy[idx];
            int nxt=dist[x][y][broken]+1;
            if(nx<0 || nx>=n || ny <0 || ny>=m) continue;
            if(board[nx][ny]=='0' && dist[nx][ny][broken]==-1) {
                dist[nx][ny][broken]=nxt;
                q.push({nx,ny,broken});
            }
            if(board[nx][ny]=='1' && broken<k && dist[nx][ny][broken+1]==-1) {
                dist[nx][ny][broken+1]=nxt;
                q.push({nx,ny,broken+1});
            }
        }
    }
    if(!escape) cout << -1;
    return 0;
}

Embed on website

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