<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

125. Shtirlits

time limit per test: 0.25 sec.
memory limit per test: 4096 KB



There is a checkered field of size N x N cells (1 Ј N Ј 3). Each cell designates the territory of a state (i.e. N2 states). Each state has an army. Let A [i, j] be the number of soldiers in the state which is located on i-th line and on j-th column of the checkered field (1£i£N, 1£j£N, 0 £  A[i, j] £  9). For each state the number of neighbors, B [i, j], that have a larger army, is known. The states are neighbors if they have a common border (i.e. 0 £  B[i, j]  £  4). Shtirlits knows matrix B. He has to determine the number of armies for all states (i.e. to find matrix A) using this information for placing forces before the war. If there are more than one solution you may output any of them.



Input

The first line contains a natural number N. Following N lines contain the description of matrix B - N numbers in each line delimited by spaces.


Output

If a solution exists, the output file should contain N lines, which describe matrix A. Each line will contain N numbers delimited by spaces. If there is no solution, the file should contain NO SOLUTION.


Sample Input

3
1 2 1
1 2 1
1 1 0
Sample Output

1 2 3
1 4 5
1 6 7
Author	: Victor G. Samoilov, Herman "Smash" Narkaytis
Resource	: 5th Southern Subregional Contest. Saratov 2002
Date	: 2002-10-10

<|response|>
1. Abridged Problem Statement
We have an N×N grid (1≤N≤3). Each cell (i,j) must be assigned an integer A[i][j] between 0 and 9. For each cell we are given B[i][j], the exact number (0–4) of its orthogonal neighbors whose A-value is strictly larger than A[i][j]. Recover any matrix A consistent with B, or report “NO SOLUTION” if none exists.

2. Key Observations
- Since N≤3, there are at most 9 cells and each A[i][j] ∈ {0,…,9}. A brute-force DFS over all assignments is feasible if we prune aggressively.
- We only care about comparisons between neighbors. When we assign a value to a cell, we can immediately update the “remaining larger-neighbor count” for already-assigned neighbors (up and left) and for the current cell itself.
- If at any point the remaining count for some cell goes negative, or if we finish assigning all of a cell’s neighbors and its remaining count ≠0, we can backtrack.

3. Full Solution Approach
a. Read N and the matrix B. Make a copy b2 = B, which will track how many larger neighbors each cell still needs as we assign A.
b. Maintain an N×N array A of assignments. We fill it in row-major order, pos=0…N*N−1, where pos→(i=pos/N, j=pos%N).
c. Define a change(i,j,delta) routine that applies delta=−1 when placing A[i][j] and delta=+1 when removing it:
   - Look at the two already-assigned neighbors: (i−1,j) and (i,j−1), if they exist.
   - If neighbor’s A > A[i][j], then that neighbor contributed one to B[i][j], so add delta to b2[i][j].
   - If A[i][j] > neighbor’s A, then the current cell contributed one to B[neighbor], so add delta to b2[neighbor].
   - The routine returns true (failure) if any touched b2 entry becomes negative.
d. Backtracking DFS(pos):
   - If pos==N*N, all cells are assigned. The only un-checked cells are those in the last row—their “down” neighbors do not exist. Check b2[last row][*] are all zero. If so, print A and exit; otherwise return.
   - Otherwise let (i,j)=pos. Try A[i][j]=0,…,9:
     1. Call change(i,j,−1). If it returns true (some b2<0) or, for i>0, the up neighbor's residual b2[i−1][j] is not yet zero, skip recursing for this value.
     2. Otherwise recurse DFS(pos+1).
     3. Undo with change(i,j,+1).
e. If DFS completes without printing a solution, output “NO SOLUTION.”

This explores at most 10^(N²) assignments in the worst case but in practice is extremely fast for N≤3 thanks to early pruning.

4. C++ Implementation
```cpp
#include <bits/stdc++.h>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

int n;
vector<vector<int>> a, b, b2;

void read() {
    cin >> n;
    b.resize(n, vector<int>(n));
    a.resize(n, vector<int>(n));
    cin >> b;
    b2 = b;
}

bool change(int i, int j, int delta) {
    bool fail = false;
    if(i > 0) {
        b2[i][j] += delta * (a[i - 1][j] > a[i][j]);
        b2[i - 1][j] += delta * (a[i - 1][j] < a[i][j]);
        if(b2[i][j] < 0 || b2[i - 1][j] < 0) {
            fail = true;
        }
    }

    if(j > 0) {
        b2[i][j] += delta * (a[i][j - 1] > a[i][j]);
        b2[i][j - 1] += delta * (a[i][j - 1] < a[i][j]);
        if(b2[i][j] < 0 || b2[i][j - 1] < 0) {
            fail = true;
        }
    }
    return fail;
}

void backtrack(int pos) {
    if(pos == n * n) {
        for(int j = 0; j < n; j++) {
            if(b2[n - 1][j] != 0) {
                return;
            }
        }

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                cout << a[i][j] << " \n"[j == n - 1];
            }
        }
        exit(0);
    }

    int i = pos / n, j = pos % n;
    for(int val = 0; val <= 9; val++) {
        a[i][j] = val;
        if(!change(i, j, -1) && (i == 0 || b2[i - 1][j] == 0)) {
            backtrack(pos + 1);
        }
        change(i, j, 1);
    }
}

void solve() {
    /*
     * Reconstruct the army matrix A by backtracking over cells in row-major
     * order, trying every digit 0..9 per cell.
     *
     * b2 is a working copy of the target neighbour-counts B that is decremented
     * as constraints get satisfied: change(i, j, delta) adjusts the counts of
     * the current cell and its already-placed up/left neighbours according to
     * which side holds the larger army. After filling a cell we require its
     * upper neighbour's residual count to be exactly zero (it can no longer
     * gain neighbours), pruning impossible branches. A full assignment whose
     * last row also has all-zero residuals is printed and the program exits.
     */

    backtrack(0);
    cout << "NO SOLUTION" << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        // cout << "Case #" << test << ": ";
        solve();
    }

    return 0;
}
```

5. Python Implementation with Detailed Comments
```python
import sys
sys.setrecursionlimit(10000)

def main():
    data = sys.stdin.read().split()
    n = int(data[0])
    B = []
    idx = 1
    for _ in range(n):
        B.append(list(map(int, data[idx:idx+n])))
        idx += n

    # A will store the army sizes; b2 the remaining larger-neighbor counts
    A = [[0]*n for _ in range(n)]
    b2 = [row[:] for row in B]

    # update(i,j,delta): apply delta=-1 to place A[i][j], +1 to remove.
    # Returns False if any b2 becomes negative.
    def update(i, j, delta):
        # Check the up and left neighbors only
        for di, dj in [(-1,0),(0,-1)]:
            x, y = i+di, j+dj
            if 0 <= x < n and 0 <= y < n:
                if A[x][y] > A[i][j]:
                    b2[i][j] += delta
                if A[i][j] > A[x][y]:
                    b2[x][y] += delta
                if b2[i][j] < 0 or b2[x][y] < 0:
                    return False
        return True

    def dfs(pos):
        if pos == n*n:
            # All cells done: check last row demands exactly zero
            if all(b2[n-1][j] == 0 for j in range(n)):
                for row in A:
                    print(" ".join(map(str,row)))
                sys.exit(0)
            return

        i, j = divmod(pos, n)
        for v in range(10):
            A[i][j] = v
            if update(i, j, -1):
                # If there's an up-neighbor, it has no more unknown neighbors now
                if i==0 or b2[i-1][j] == 0:
                    dfs(pos+1)
            update(i, j, +1)

    dfs(0)
    print("NO SOLUTION")

if __name__ == "__main__":
    main()
```
