#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
const int maxN = 1000;
int grid[maxN][maxN];
bool visited[maxN][maxN][2];
int last[maxN][maxN];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
int dis[maxN][maxN]={};
int n;
bool valid(int x, int y, int l){
return x >= 0 && x < n && y >= 0 && y < n && visited[x][y][l] == 0;
}
signed main(){
cin >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin >> grid[i][j];
queue<pair<int, int>> bfs;
bfs.push({0, 0});
dis[0][0] = 1;
visited[0][0][0] = 1;
visited[0][0][1] = 1;
while(!bfs.empty()){
int x = bfs.front().f;
int y = bfs.front().s;
bfs.pop();
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(!x && !y){
if(!valid(nx, ny, (grid[x][y] > grid[nx][ny]))) continue;
visited[nx][ny][(grid[x][y] > grid[nx][ny])] = 1;
last[nx][ny] = ((grid[x][y] > grid[nx][ny]) ? -1: 1);
dis[nx][ny] = dis[x][y] + 1;
bfs.push({nx, ny});
}else{
if(!valid(nx, ny, (grid[x][y] > grid[nx][ny])) || (grid[x][y] > grid[nx][ny]) == last[x][y]) continue;
visited[nx][ny][(grid[x][y] > grid[nx][ny])] = 1 ;
last[nx][ny] = (grid[x][y] > grid[nx][ny] ? -1: 1);
dis[nx][ny] = dis[x][y] + 1;
bfs.push({nx, ny});
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cout << dis[i][j];
}cout << endl;
}cout << endl;
}
}
cout << visited[1][1][0];
cout << (dis[n - 1][n - 1]? dis[n - 1][n - 1]: -1);
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiNkZWZpbmUgZiBmaXJzdAojZGVmaW5lIHMgc2Vjb25kCmNvbnN0IGludCBtYXhOID0gMTAwMDsKaW50IGdyaWRbbWF4Tl1bbWF4Tl07CmJvb2wgdmlzaXRlZF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