本文共 1613 字,大约阅读时间需要 5 分钟。
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.
Java代码:
public class Solution {boolean[][] row = new boolean[9][9];boolean[][] col = new boolean[9][9];boolean[][] blo = new boolean[9][9];public void solveSudoku(char[][] board) { for(int i=0;i<9;i++) for(int j =0;j<9;j++){ int temp =board[i][j]-'1'; if(board[i][j]!='.'){ row[i][temp]=true; col[j][temp]=true; blo[3*(i/3)+j/3][temp]=true; } } solveHelper(0,0,board);}public boolean solveHelper(int i, int j, char[][] board){ if(i==9) return true; if(board[i][j]!='.'){ if(j<8) return solveHelper(i,j+1,board); else return solveHelper(i+1,0,board); }else for(int k =0;k<9;k++){ if(row[i][k]==false&&col[j][k]==false&&blo[3*(i/3)+j/3][k]==false){ board[i][j] = (char)(k+'0'+1); row[i][k]=true; col[j][k]=true; blo[3*(i/3)+j/3][k]=true; if(j<8&&solveHelper(i,j+1,board)) return true; else if(j==8&&solveHelper(i+1,0,board)) return true; else{ board[i][j] = '.'; row[i][k]=false; col[j][k]=false; blo[3*(i/3)+j/3][k]=false; } } } return false;}}
转载地址:http://nvuni.baihongyu.com/