|
deepseek的解答,我用中文提问的,不知为何出来英文答案
# SQL Solution for Minesweeper Game
Here's a SQL solution that implements the Minesweeper game by calculating the numbers around mines based on the input string:
- WITH
- -- Parse input string into a grid table with row/column coordinates
- grid AS (
- SELECT
- row_num,
- col_num,
- CASE WHEN SUBSTR(:v_str, (row_num-1)*(:v_width+1) + col_num, 1) = '*' THEN '*'
- ELSE ' ' END AS cell
- FROM (
- SELECT LEVEL AS row_num FROM DUAL CONNECT BY LEVEL <= :v_height
- ) rows
- CROSS JOIN (
- SELECT LEVEL AS col_num FROM DUAL CONNECT BY LEVEL <= :v_width
- ) cols
- ),
- -- Identify all mine positions
- mines AS (
- SELECT row_num, col_num
- FROM grid
- WHERE cell = '*'
- ),
- -- For each cell, count adjacent mines
- counts AS (
- SELECT
- g.row_num,
- g.col_num,
- CASE
- WHEN g.cell = '*' THEN '*'
- ELSE (
- SELECT COUNT(*)
- FROM mines m
- WHERE m.row_num BETWEEN g.row_num-1 AND g.row_num+1
- AND m.col_num BETWEEN g.col_num-1 AND g.col_num+1
- AND (m.row_num != g.row_num OR m.col_num != g.col_num)
- AND m.row_num BETWEEN 1 AND :v_height
- AND m.col_num BETWEEN 1 AND :v_width
- )
- END AS value
- FROM grid g
- ),
- -- Format the counts (replace 0 with space)
- formatted AS (
- SELECT
- row_num,
- col_num,
- CASE
- WHEN value = '*' THEN '*'
- WHEN value = 0 THEN ' '
- ELSE TO_CHAR(value)
- END AS cell
- FROM counts
- )
- -- Assemble the final output string
- SELECT LISTAGG(line, ' ') WITHIN GROUP (ORDER BY row_num) AS result
- FROM (
- SELECT
- row_num,
- LISTAGG(cell, '') WITHIN GROUP (ORDER BY col_num) AS line
- FROM formatted
- GROUP BY row_num
- );
复制代码
This solution:
1. Parses the input string into a grid table with row/column coordinates
2. Identifies all mine positions
3. For each cell, counts how many mines are in adjacent cells (including diagonals)
4. Formats the results - keeping '*' for mines, numbers for adjacent counts, and spaces for 0
5. Reassembles the grid into the output string format
The solution handles edge cases correctly (cells on borders/corners have fewer adjacent cells) and produces the required output format. |
|