#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 hx[]={-2, -1, 1, 2, 2, 1, -1, -2};
int hy[]={1, 2, 2, 1, -1, -2, -2, -1};
int n;
int board[205][205];
int dist[205][205][31];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int escape=0;
    int k,n,m;
    cin >> k;
    cin >> m >> n;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin >>board[i][j];
        }
    }
    memset(dist,-1,sizeof(dist));
    queue<tuple<int,int,int>> q;
    q.push({0,0,0});
    dist[0][0][0]=0;
    while(!q.empty()) {
        int x,y,jump;
        tie(x,y,jump)=q.front();q.pop();
        if(x==n-1 && y==m-1) {
            cout << dist[x][y][jump];
            escape=1;
            break;
        }
        int nxt=dist[x][y][jump]+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(board[nx][ny]==1 || dist[nx][ny][jump]!=-1) continue;
            q.push({nx,ny,jump});
            dist[nx][ny][jump]=nxt;
        }
        if(jump<k) {
            for(int idx=0; idx<8; idx++) {
                int nx=x+hx[idx];
                int ny=y+hy[idx];
                if(nx<0 || nx>=n || ny<0 || ny>=m) continue;
                if(board[nx][ny]==1 || dist[nx][ny][jump+1]!=-1) continue;
                q.push({nx,ny,jump+1});
                dist[nx][ny][jump+1]=nxt;
            }
        }
    }
    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: