Hitori is a number-grid puzzle in which you must shade certain cells black so that the remaining white cells follow specific rules. You are given an n x n integer matrix called grid. Your task is to solve the Hitori puzzle and return an n x n matrix representing the solution.
Each cell in the resulting matrix must contain:
- 0 : The cell is shaded black.
- 1 : The cell remains white.
The resulting grid must satisfy all the following rules:
- No Repeated Numbers in Rows: No number should appear more than once among the white cells of any row.
- No Repeated Numbers in Columns: No number should appear more than once among the white cells of any column.
- No Adjacent Black Cells: Two black cells must never share an edge. Diagonal adjacency is allowed.
- All White Cells Must Be Connected: Every white cell must be reachable from every other white cell by moving up, down, left, or right through white cells.
- Only Duplicate Cells Can Be Shaded: A cell can be shaded black only if its number occurs more than once in its row or column.
Return the resulting matrix representing the solved puzzle. Note: Every puzzle is guaranteed to have exactly one valid solution.
Examples
Example 1
Input: grid = [[2,1,2],
[1,2,2],
[3,3,1]]
Output: [[0,1,1],
[1,1,0],
[0,1,1]]
Explanation:
The cells marked 0 are shaded black. The remaining white cells contain no duplicate numbers in any row or column, no two black cells share an edge, and all white cells remain connected.
Example 2
Input: grid = [[2,1,4,2],
[3,2,1,2],
[3,3,2,1],
[1,2,2,3]]
Output: [[1,1,1,0],
[1,0,1,1],
[0,1,1,1],
[1,1,0,1]]
Explanation:
The output identifies the cells that must be shaded black to eliminate duplicate numbers while satisfying the adjacency and connectivity rules.
Example 3
Input: grid = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: [[1,1,1],
[1,1,1],
[1,1,1]]
Explanation:
Every number is distinct within its row and column. Therefore, no cells need to be shaded black, and all cells remain white.
Constraints
- 1 ≤ n ≤ 10
- grid.length == n
- grid[i].length == n
- 1 ≤ grid[i][j] ≤ 10⁹