Sudoku Puzzles - 九宫格(数独)游戏

每行必须只有出现一次的1到9。eg: 

192354867

每列必须只出现一次的1到9. eg:

1
4
5
2
9
7
8
6
3

并且,1-9 必须在每9个小框格内只出现一次。



题记:《最强大脑》中有个小女生,填写更大的九宫格游戏,而且现场是自己算出来的。好厉害。 查了下,她被称为 数独天才孙彻然。

视频地址是:http://v.youku.com/v_show/id_XNjk0OTE4NzA0.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用递归函数和回溯算法来解决九宫格数独问题。以下是一个简单的 Python 代码示例: ```python def solve(board): """ Solve the Sudoku puzzle using recursive backtracking. :param board: 2D list of integers representing the Sudoku puzzle :return: boolean indicating if the puzzle is solved """ empty_cell = find_empty(board) if not empty_cell: return True row, col = empty_cell for num in range(1, 10): if is_valid(board, row, col, num): board[row][col] = num if solve(board): return True board[row][col] = 0 return False def find_empty(board): """ Find an empty cell in the Sudoku puzzle. :param board: 2D list of integers representing the Sudoku puzzle :return: tuple containing the row and column of an empty cell, or None if there are no empty cells """ for row in range(9): for col in range(9): if board[row][col] == 0: return (row, col) return None def is_valid(board, row, col, num): """ Check if a number can be placed in a given cell in the Sudoku puzzle. :param board: 2D list of integers representing the Sudoku puzzle :param row: integer representing the row of the cell to check :param col: integer representing the column of the cell to check :param num: integer representing the number to check :return: boolean indicating if the number can be placed in the cell """ # Check row for i in range(9): if board[row][i] == num: return False # Check column for i in range(9): if board[i][col] == num: return False # Check square square_row = (row // 3) * 3 square_col = (col // 3) * 3 for i in range(square_row, square_row + 3): for j in range(square_col, square_col + 3): if board[i][j] == num: return False return True ``` 使用该函数,您可以通过以下方式调用它: ```python board = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] solve(board) for row in board: print(row) ``` 该代码将打印已解决数独的完整板。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值