package com.sogou.hadoop.test; public class Sudoku {
/**
验证该值是否合法
*/ public boolean isValidSudoku(char[][] board,int x,int y){ int row,col; //same value in the same column for(row=0;row<9;row++){ if((x!=row)&&(board[row][y]==board[x][y])){ return false; } } // same value in the same row for(col=0;col<9;col++){ if((y!=col)&&board[x][col]==board[x][y]) 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]==board[x][y]) return false; } } return true; }
//递归调用该方法,没有检测已经填写的数字而是从头开始 public boolean solveSudoku(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(solveSudoku(board)) return true; } board[row][col]=‘.‘; } return false; } } } return true; } public static void main(String[] args) { } }