www.dotcpp.com/oj/problem3…
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
const int N = 15;
int n, k;
int g[N][N];
bool st[N][N];
int p[N][N];
vector<int> path;
int dx[8] = { -1, -1, 0, 1, 1, 1, 0, -1 };
int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
bool dfs(int x, int y, int cnt)
{
for (int i = 0; i < 8; ++i)
{
int tx = x + dx[i], ty = y + dy[i];
if (tx < 0 || ty < 0 || tx >= n || ty >= n || st[tx][ty] || !(g[x][y] == k - 1 && g[tx][ty] == 0 || g[tx][ty] == g[x][y] + 1))
continue;
if (i == 1 && (p[x - 1][y] == 3 || p[x][y + 1] == 7))
continue;
if (i == 3 && (p[x][y + 1] == 5 || p[x + 1][y] == 1))
continue;
if (i == 5 && (p[x + 1][y] == 7 || p[x][y - 1] == 3))
continue;
if (i == 7 && (p[x][y - 1] == 1 || p[x - 1][y] == 5))
continue;
p[x][y] = i;
st[tx][ty] = true;
path.push_back(i);
if (tx == n - 1 && ty == n - 1 && cnt == n * n - 1)
return true;
if (dfs(tx, ty, cnt + 1))
return true;
path.pop_back();
st[tx][ty] = false;
p[x][y] = -1;
}
return false;
}
void solve()
{
cin >> n >> k;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
{
cin >> g[i][j];
p[i][j] = -1;
}
if (g[0][0] != 0)
{
puts("-1");
return;
}
st[0][0] = true;
if (dfs(0, 0, 1))
{
for (auto x : path)
cout << x;
cout << endl;
}
else
cout << -1 << endl;
}
int main()
{
int t = 1;
while (t--)
solve();
}
