|
让deepseek把43楼SQL改成的python,一次成功
- import itertools
- from typing import List, Dict, Any
- def sql_to_python(width: int, height: int, grid_str: str):
- # CTE 1: cells
- cells = [
- {
- 'cell_id': i,
- 'r': (i - 1) // width + 1,
- 'c': (i - 1) % width + 1,
- 'cnt': grid_str[i-1] if i <= len(grid_str) else ' '
- }
- for i in range(1, width * height + 1)
- ]
-
- # CTE 2: cells2
- cells2 = []
- for cell in cells:
- cnt = cell['cnt']
- r = cell['r']
- c = cell['c']
- cell_id = cell['cell_id']
-
- # 处理cnt值
- if cnt == ' ':
- cnt_val = 0
- elif cnt == '*':
- cnt_val = None
- else:
- cnt_val = int(cnt) if cnt.strip() else None
-
- # 计算n_id
- if r > 1 and c > 1:
- n_id = cell_id - width - 1
- elif r > 1:
- n_id = cell_id - width
- elif c > 1:
- n_id = cell_id - 1
- else:
- n_id = None
-
- cells2.append({
- 'cell_id': cell_id,
- 'r': r,
- 'c': c,
- 'cnt': cnt_val,
- 'n_id': n_id,
- 'n_r': r - 1 if r > 1 else r,
- 'n_c': c - 1 if c > 1 else c
- })
-
- # CTE 3: empty_cells
- empty_cells = []
- # 先筛选出空单元格(cnt=0)
- empty_candidates = [cell for cell in cells2 if cell['cnt'] == 0]
-
- # 按SQL中的ORDER BY排序
- empty_candidates.sort(key=lambda x: (
- 9999 if x['cell_id'] > 2 * width else x['c'],
- 9999 if x['cell_id'] > 2 * width else x['r'],
- x['cell_id']
- ))
-
- for idx, cell in enumerate(empty_candidates, 1):
- r = cell['r']
- c = cell['c']
- cell_id = cell['cell_id']
- n_id = cell['n_id']
- n_r = cell['n_r']
- n_c = cell['n_c']
-
- # 计算邻居ID
- n1 = n_id - width - 1 if (n_r > 1 and n_c > 1) else 999999
- n2 = n_id - width if n_r > 1 else 999999
- n3 = n_id - width + 1 if (n_r > 1 and n_c < width) else 999999
- n4 = n_id - 1 if n_c > 1 else 999999
- n6 = n_id + width - 1 if (n_r < height and n_c > 1) else 999999
-
- # 计算n_cnt
- if n_id is None or n_id < 1 or n_id > width * height:
- n_cnt = 0
- else:
- neighbor_char = grid_str[n_id-1]
- if neighbor_char == '*' or not neighbor_char.strip():
- n_cnt = 0
- else:
- n_cnt = int(neighbor_char)
-
- # 计算en1, en2, en4
- en1 = cell_id - width - 1 if (r > 1 and c > 1 and grid_str[cell_id - width - 2] == ' ') else 0
- en2 = cell_id - width if (r > 1 and grid_str[cell_id - width - 1] == ' ') else 0
- en4 = cell_id - 1 if (c > 1 and grid_str[cell_id - 2] == ' ') else 0
-
- empty_cells.append({
- **cell,
- 'empty_id': idx,
- 'n1': n1,
- 'n2': n2,
- 'n3': n3,
- 'n4': n4,
- 'n6': n6,
- 'n_cnt': n_cnt,
- 'en1': en1,
- 'en2': en2,
- 'en4': en4
- })
-
- # CTE 4: guess
- guess = [{'mine': 0}, {'mine': 1}]
-
- return {
- 'cells': cells,
- 'cells2': cells2,
- 'empty_cells': empty_cells,
- 'guess': guess
- }
- def solve_minesweeper(width: int, height: int, grid_str: str, total_mines: int):
- # 使用之前定义的函数生成基础数据
- data = sql_to_python(width, height, grid_str)
- empty_cells = data['empty_cells']
- guess = data['guess']
-
- # 递归基 case
- recursive_t = [{
- 'm_cnt': 0,
- 'empty_id': 1,
- 'res': grid_str
- }]
-
- max_empty_id = max([ec['empty_id'] for ec in empty_cells]) if empty_cells else 0
-
- # 使用循环模拟递归(避免Python递归深度限制)
- while True:
- new_rows = []
- for t in recursive_t:
- current_empty_id = t['empty_id']
- if current_empty_id > max_empty_id:
- continue
-
- # 找到当前empty_id对应的empty_cell
- current_ec = next((ec for ec in empty_cells if ec['empty_id'] == current_empty_id), None)
- if not current_ec:
- continue
-
- # 与guess做笛卡尔积
- for g in guess:
- mine = g['mine']
-
- # 检查WHERE条件
- if not (t['m_cnt'] + mine <= total_mines):
- continue
-
- # 第一个条件:e.cell_id = 1
- if current_ec['cell_id'] == 1:
- pass # 满足条件
- else:
- # 复杂条件检查
- n_cnt = current_ec['n_cnt']
- res = t['res']
-
- # 计算CASE WHEN e.n_cnt = 0...部分
- if n_cnt == 0:
- case_val = 1 if (current_ec['n_id'] <= len(res) and res[current_ec['n_id'] - 1] == '*') else 0
- else:
- # 计算各个邻居的雷数
- mine_count = 0
- for n in ['n1', 'n2', 'n3', 'n4', 'n6']:
- n_pos = current_ec[n]
- if n_pos <= len(res) and res[n_pos - 1] == '*':
- mine_count += 1
-
- case_val = 1 if mine_count < n_cnt else 0
-
- # 检查主条件
- if case_val != mine:
- continue
-
- # 检查en1, en2, en4条件
- valid = True
- for en in ['en1', 'en2', 'en4']:
- en_pos = current_ec[en]
- if en_pos > 0:
- if en_pos > len(res):
- valid = False
- break
- en_val = 1 if res[en_pos - 1] == '*' else 0
- if en_val != mine:
- valid = False
- break
- if not valid:
- continue
-
- # 构建新行
- new_res = (
- t['res'][:current_ec['cell_id'] - 1] +
- ('*' if mine == 1 else ' ') +
- t['res'][current_ec['cell_id']:]
- )
-
- new_rows.append({
- 'm_cnt': t['m_cnt'] + mine,
- 'empty_id': current_empty_id + 1,
- 'res': new_res
- })
-
- if not new_rows:
- break
-
- # 添加新行到递归表(替换原有内容以模拟递归)
- recursive_t = new_rows
-
- # 筛选最终结果
- solutions = [t['res'] for t in recursive_t if t['m_cnt'] == total_mines]
- return solutions
- # 使用示例
- if __name__ == "__main__":
- width, height,total_mines,grid_str =9,9,27,' 2**2 2* 3**3 3* 3**3 3* 3**3 3* 3**3 3* 3**3 3* 3**3 3* 3**3 3* 2**2 2*'.replace('*', ' ')
- solutions = solve_minesweeper(width, height, grid_str, total_mines)
- print(f"找到 {len(solutions)} 个解:")
- for i, sol in enumerate(solutions, 1):
- print(f"解 {i}: {sol}")
复制代码 |
|