标签:
题目地址:https://leetcode.com/problems/sudoku-solver/
题目解析:使用最笨的办法,行优先遍历需要填的空,使用1到9去尝试,然后判断是否符合条件;如果不符合条件则尝试下一个数字,如果符合条件则尝试下一个需要填的空。使用递归方法实现。
题目解答:
public class Solution { public void solveSudoku(char[][] board) { solveSudoku(board,0,0); } public boolean solveSudoku(char[][] board,int row,int column){ if(row >= 9){ return true; } if(column >= 9){ return solveSudoku(board,row+1,0); } if(board[row][column] == ‘.‘){ for(int k = 1;k<=9;k++){ board[row][column] = (char)(‘0‘+k); if(isValid(board,row,column)&&solveSudoku(board,row,column+1)){ return true; } board[row][column] = ‘.‘; } return false; }else { return solveSudoku(board,row,column+1); } } private boolean isValid(char[][] board,int row,int column){ for(int i = 0;i<9;i++){ if(i!=row && board[i][column] == board[row][column]){ return false; } } for(int i = 0;i<9;i++){ if(i!=column && board[row][i] == board[row][column]){ return false; } } int boxStartRow = (row/3)*3; int boxStartColumn = (column/3)*3; for(int i = boxStartRow;i<boxStartRow+3;i++){ for(int j = boxStartColumn;j<boxStartColumn+3;j++){ if(i!=row&&j!=column&&board[i][j]==board[row][column]){ return false; } } } return true; } }
标签:
原文地址:http://www.cnblogs.com/xiongyuesen/p/4424848.html