Nurikabe
Time limit1sMemory limit128 MB
Solve Nurikabe puzzles on grids up to 9x9 by coloring cells black or white so all six connectivity and counting rules hold.
- Level
Hard8 of 10
- Topics
- Backtracking, DFS, Implementation, Brute force
- Solved
- No attempts yet
Problem
Write a program that solves Nurikabe puzzles.
Nurikabe is played on a rectangular grid. Each cell is either empty (shown as .) or contains a single-digit number. To solve the puzzle you must color every cell either white (land) or black (sea) so that all of the following conditions hold. An island is a maximal group of white cells connected horizontally or vertically.
- All black cells must be connected to one another.
- Every numbered cell must belong to some island.
- The number of white cells in each island must equal the number written in that island.
- Every island must contain exactly one numbered cell.
- No two different islands may be adjacent (connected) to each other.
- No area may be entirely black.
Cells are considered adjacent only horizontally or vertically, never diagonally. Every input is guaranteed to have a unique solution.
Input
The input consists of several test cases.
The first line of each test case contains the puzzle dimensions and , separated by a space. ()
Each of the next lines describes the initial state of the puzzle. Each line has characters: an empty cell is given as ., and a numbered cell is given as its digit. Every number is a single digit.
The last line of the input contains two zeros, marking the end of the input.
Output
For each test case, print the solved puzzle. Print each black cell as #, and print each white cell as its original character (. or its digit). Print one blank line between the outputs of consecutive puzzles.