Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character ‘.‘
.
Assume that there would be is only one unique solution.
A Sudoku Puzzle ...
... and its solution numbers marked in red.
idea 1: Use a violent Dfs
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 (b OARD[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);}}
Idea 2: Use dancing Links, and then fill in the code.
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
Leetcode Sudoku Solver