[leetcode] Sudoku Solver
来源:互联网 发布:黑九月 知乎 编辑:程序博客网 时间:2024/06/01 17:25
from : https://leetcode.com/problems/sudoku-solver/
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.
A sudoku puzzle...
...and its solution numbers marked in red.
public class Solution { public void solveSudoku(char[][] board) { internalSolveSudoku(board); } private boolean internalSolveSudoku(char[][] board) { for (int row = 0; row < 9; ++row) { for (int col = 0; col < 9; ++col) { if ('.' == board[row][col]) { for (int i = 1; i <= 9; ++i) { board[row][col] = (char) ('0' + i); if (isValidSudoku(board, row, col)) { if (internalSolveSudoku(board)) { return true; } } board[row][col] = '.'; } return false; } } } return true; } private boolean isValidSudoku(char[][] board, int x, int y) { int row, col; int v = board[x][y]; // Same value in the same column? for (row = 0; row < 9; ++row) { if ((x != row) && (board[row][y] == v)) { return false; } } // Same value in the same row? for (col = 0; col < 9; ++col) { if ((y != col) && (board[x][col] == v)) { return false; } } // Same value in the 3 * 3 block it belong to? for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) { for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) { if ((x != row || y != col) && (board[row][col] == v)) { return false; } } } return true; }}
public class Solution { public void solveSudoku(char[][] board) { fillSudoku(board); } private boolean fillSudoku(char[][] bd) { for(int i=0; i<9; ++i) { for(int j=0; j<9; ++j) { if(bd[i][j] == '.') { for(int k=1; k<10; ++k) { bd[i][j] = (char)('0'+k); if(validSudoku(bd, i, j, bd[i][j])) { if(fillSudoku(bd)) { return true; } } bd[i][j] = '.'; } return false; } } } return true; } private boolean validSudoku(char[][] bd, int x, int y, char k) { for(int i=0; i<9; ++i) { if(i != x && k == bd[i][y] || i != y && k == bd[x][i]) { return false; } } for(int i=x/3*3, li = i+3; i<li; ++i) { for(int j=y/3*3, lj = j+3; j<lj; ++j) { if((i != x || j != y) && k == bd[i][j]) { return false; } } } return true; } }
0 0
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & 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
- LeetCode - Sudoku Solver
- LeetCode:Sudoku Solver
- 【leetcode】Sudoku Solver
- Leetcode: Sudoku Solver
- leetcode Sudoku Solver
- LeetCode | Sudoku Solver
- LeetCode Sudoku Solver
- [Leetcode] Sudoku Solver (Java)
- Android核心基础-8.Android四大组件之Activity-2.关闭、传递数据
- Redis 5种数据类型,2种特殊数据处理策略
- light oj 1017 Brush (III)
- [经典书籍]编程经典书籍
- 字符串的排列和组合代码 C++
- [leetcode] Sudoku Solver
- 使用SpannableString设置部分文字大小、颜色、超链接、点击事件
- ubuntu中文手册安装
- POJ_3254_Corn Fields
- osgi2——camel网关调用其它系统webservice
- Number of 1 Bits
- IOS第四节:OC中的内存管理机制
- 详解计算机主机网关的作用
- KMP求循环节问题