Back to challenges
Medium 0 solved 0% acceptance

Minesweeper Neighbor Counts

Annotate a rectangular board.

What you'll learn

  • Visit the 8 neighbors of a cell
  • Stay inside the grid boundaries
  • Build an annotated copy of a board

Problem

Annotate a rectangular board. A star (*) is a mine and a dot (.) is a safe cell. For each safe cell, count mines in the eight surrounding cells, including diagonals. Replace it with the count from 1 to 8, or keep a dot if the count is zero. Preserve every mine. Cells outside the board do not exist.

Implement minesweeper_neighbor_counts(board).

Input

board: The rows from top to bottom; characters run left to right.

Output

Return the annotated rows in the same order and dimensions.

Constraints

1 ≤ rows, columns ≤ 200. Every row has the same nonzero length and contains only * and . .

Examples

Example 1
Input:
board = ["*..", "...", "..*"]

Expected output:
expected = ["*1.", "121", ".1*"]
Input:
std::vector<std::string> board = {"*..", "...", "..*"};

Expected output:
std::vector<std::string> expected = {"*1.", "121", ".1*"};
Input:
string[] board = new string[] {"*..", "...", "..*"};

Expected output:
string[] expected = new string[] {"*1.", "121", ".1*"};

Explanation

The center touches both mines, so its count is 2. The top-right and bottom-left touch none and stay dots. Other safe cells touch one mine.

Example 2
Input:
board = ["..."]

Expected output:
expected = ["..."]
Input:
std::vector<std::string> board = {"..."};

Expected output:
std::vector<std::string> expected = {"..."};
Input:
string[] board = new string[] {"..."};

Expected output:
string[] expected = new string[] {"..."};

Explanation

This one-row board has no mines. All counts are zero, so every dot remains a dot.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Only safe cells change; mines stay exactly where they are.

Hint 2

For each dot, inspect the eight surrounding positions and count nearby mines.

Hint 3

Be careful near edges and corners so you do not read outside the board.

Expected complexity

O(r*c) time, O(r*c) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.