https://www.acmicpc.net/problem/1600
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
struct MOVE { int x, y; };
MOVE mv[4] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
MOVE hmv[8] = { { -2,-1 },{ -1,-2 },{ 1,-2 },{ 2,-1 },{ -2,1 },{ -1,2 },{ 1,2 },{ 2,1 } };
const int MAX = 205;
int map[MAX][MAX];
int K;
int answer = 2e9;
int w, h;
int visited[MAX][MAX][35];
struct INFO { int ci, cj, count, way; };
int main(void) {
cin >> K;
cin >> h >> w;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
cin >> map[i][j];
}
}
queue<INFO> q;
memset(visited, -1, sizeof(visited));
q.push({0,0,0,0});
visited[0][0][0] = 0;
while (!q.empty()) {
int ci = q.front().ci;
int cj = q.front().cj;
int count = q.front().count;
int way = q.front().way;
q.pop();
if (ci == (w - 1) && cj == (h - 1)) {
answer = min(answer, way);
break;
}
if (count < K) {
for (int k = 0; k < 8; k++) {
int movei = ci + hmv[k].x;
int movej = cj + hmv[k].y;
if (!(movei >= 0 && movei < w && movej >= 0 && movej < h)) continue;
if (map[movei][movej] == 1) continue;
if (visited[movei][movej][count+1] == -1) {
visited[movei][movej][count + 1] = way + 1;
q.push({ movei, movej, count + 1, way + 1 });
}
}
}
for (int k = 0; k < 4; k++) {
int movei = ci + mv[k].x;
int movej = cj + mv[k].y;
if (!(movei >= 0 && movei < w && movej >= 0 && movej < h)) continue;
if (map[movei][movej] == 1) continue;
if (visited[movei][movej][count] == -1) {
visited[movei][movej][count] = way + 1;
q.push({ movei, movej, count, way + 1 });
}
}
}
if (answer == 2e9) answer = -1;
cout << answer << endl;
}