leetcode解题方案--037-- Sudoku Solver
来源:互联网 发布:北京市大兴区 阿里云 编辑:程序博客网 时间:2024/06/03 19:50
题目
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.’.
You may assume that there will be only one unique solution.
分析
回溯法,挨个试
不用考虑时间复杂度。这种解放人类大脑的题基本都需要计算机累一点。
写了一个不忍直视的递归。
应该会有简化的方法。
class Solution { public static void solveSudoku(char[][] board) { if (board[0][0] != '.') { testAdd(board, 0, 0); } else { char init = '1'; while (init <= '9') { board[0][0] = init; if (testAdd(board, 0, 0)) { break; } else { init++; } } } for (int i = 0; i < 9; i++) { System.out.println(Arrays.toString(board[i])); } } public static boolean testAdd(char[][] board, int x, int y) { //验证xy位置的正确性 char cur = board[x][y]; for (int i = 0; i < 9; i++) { if (board[i][y] == cur && i != x) { return false; } if (board[x][i] == cur && i != y) { return false; } } int xblock = x / 3; int yblock = y / 3; for (int i = xblock * 3; i < xblock * 3 + 3; i++) { for (int j = yblock * 3; j < yblock * 3 + 3; j++) { if (board[i][j] == cur && ((i != x) || (j != y))) { return false; } } } int newx = -1, newy = -1; for (int i = x; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { newx = i; newy = j; break; } } if (newx != -1) { break; } } if (newx == -1 && newy == -1) { return true; } char testchar = '0'; do { testchar++; board[newx][newy] = testchar; if (testAdd(board, newx, newy) == true) { return true; } } while (testchar < '9'); board[newx][newy] = '.'; return false; }}
阅读全文
0 0
- leetcode解题方案--037-- Sudoku Solver
- [LeetCode]037-Sudoku Solver
- LeetCode 037 Sudoku Solver
- [leetcode] 37. Sudoku Solver 解题报告
- [Leetcode] 37. Sudoku Solver 解题报告
- [leetcode]37. Sudoku Solver@Java解题报告
- Sudoku Solver解题报告
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & Sudoku Solver
- leetcode 037 —— Sudoku Solver
- Leetcode 37 Sudoku Solver
- [Leetcode] Sudoku Solver
- Leetcode 37: Sudoku solver
- LeetCode Sudoku Solver
- [LeetCode]Sudoku Solver
- Leetcode Sudoku Solver
- LeetCode-Sudoku Solver
- ADIL验证授权
- nginx root、alias、location指令使用方法
- Linux卷操作的步骤
- TensorFLow 数学运算
- Oracle常见问题解决_ORA_28040
- leetcode解题方案--037-- Sudoku Solver
- Hadoop打Jar 及运行jar
- window.onload
- 浅谈MVC、MVP、MVVM架构模式的区别和联系
- 【Tensorflow slim】slim layers包
- java实现下载并选择保存路径
- BaseRecyclerViewAdapterHelper 实现不同条目的列表
- 根据byte计算文件大小
- hdu 2066 迪杰斯特拉算法入门