Nurikabe
InterviewTime limit1sMemory limit256 MB
Check whether each numbered island has the required size, all water cells connect, and no 2 by 2 block is all water.
- Level
Medium4 of 10
- Topics
- BFS, Matrix, Implementation
- Solved
- No attempts yet
Problem

Nurikabe is a pencil puzzle from Japan. You are given a rectangular grid. Each cell is either an island cell (white) or a water cell (black), and some island cells carry a number from 1 to 9. A board is filled in correctly when all three rules below hold.
- Two cells are adjacent when they share a side. Island cells that reach each other along adjacent island cells form one island. Every island contains exactly one numbered cell, and the number of cells in that island equals that number.
- All water cells are connected into one group under the same adjacency rule.
- No 2×2 block consists of four water cells. Every 2×2 block of the grid contains at least one island cell.
Decide whether a filled board is correct.
A rule with nothing to apply to holds. A board with no water cell satisfies the second rule, and a board with one row or one column has no 2×2 block.
Input
The first line contains , the number of boards.
The first line of each board contains the row count and the column count , separated by a space. The next lines contain the rows of the board, one row per line. Each row is a string of characters from 123456789.#, where # is a water cell, a digit is a numbered island cell, and . is an island cell without a number.
Output
For each board, print YES on its own line if the board is filled in correctly, and NO otherwise.