标签:
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 { private boolean isValidSudoku(char[][] board, int row, int column) { int i, j; int[] valid1 = new int[10]; int[] valid2 = new int[10]; int[] valid3 = new int[10]; for (i = 0; i <9; i++) { if (board[i][column] != '.') { if (valid1[board[i][column] - '0'] > 0) return false; valid1[board[i][column] - '0']++; } if (board[row][i] != '.') { if (valid2[board[row][i] - '0'] > 0) return false; valid2[board[row][i] - '0']++; } } for (i = (row / 3) * 3; i < (row / 3 + 1) * 3; i++) { for (j = (column / 3) * 3; j < (column / 3 + 1) * 3; j++) { if (board[i][j] != '.') { if (valid3[board[i][j] - '0'] > 0) return false; valid3[board[i][j] - '0']++; } } } return true; } private boolean internalSolveSudoku(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { for (int k = 1; k <= 9; k++) { board[i][j] = (char) ('0' + k); if (isValidSudoku(board, i, j)) { if (internalSolveSudoku(board)) { return true; } } board[i][j] = '.'; return false; } } } } return true; } public void solveSudoku(char[][] board) { internalSolveSudoku(board); } }思路2:使用Dancing Links,代码后补。
版权声明:本文博客原创文章。博客,未经同意,不得转载。
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4632527.html