Solve the following coding problems.
Problem 1: Generate and Print a Minesweeper Board
You are given integers rows, cols, and mineCount. Generate a rows x cols Minesweeper board containing exactly mineCount mines placed at random distinct cells.
Represent the board as a 2D array of characters:
-
'*'
represents a mine.
-
A digit
'0'
through
'8'
represents the number of adjacent mines around that cell.
Adjacent cells include all 8 directions: horizontal, vertical, and diagonal.
Return or print the completed board.
Example:
Input:
rows = 3, cols = 4, mineCount = 2
One possible output:
0 1 * 1
0 1 1 1
0 0 0 0
Because the mines are placed randomly, multiple valid outputs are possible.
Clarify how you would handle invalid input, such as mineCount > rows * cols.
Problem 2: Search for a Word in a Straight Line
You are given a 2D grid of characters and a target word. Determine whether the word appears in the grid in a single straight line.
The word may be read in any of the 8 directions:
-
left to right
-
right to left
-
top to bottom
-
bottom to top
-
the 4 diagonal directions
A valid match must use consecutive cells in one fixed direction. You may not turn while matching the word.
Return true if the word exists; otherwise return false.
Example:
Grid:
A B C E
S F C S
A D E E
word = "ABCC"
Output: false
word = "SEE"
Output: true
Problem 3: Search for a Word by Adjacent Cells
You are given a 2D grid of characters and a target word. Determine whether the word can be formed by moving between horizontally or vertically adjacent cells.
Rules:
-
Each step may move up, down, left, or right.
-
The same cell may not be used more than once in a single word path.
-
Return
true
if the word can be formed; otherwise return
false
.
Example:
Grid:
A B C E
S F C S
A D E E
word = "ABCCED"
Output: true
word = "SEE"
Output: true
word = "ABCB"
Output: false