码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--Sudoku Solver

时间:2014-07-06 16:07:23      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:blog   http   java   art   for   io   

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.

bubuko.com,布布扣

A sudoku puzzle...

 

bubuko.com,布布扣

...and its solution numbers marked in red.

 

This is a simple problem on dfs method

public class Solution {
    public void solveSudoku(char[][] board){
        List<Integer> blankCells = new ArrayList<Integer>();
		//a sudoku board is a 9 by 9 array
		for(int i = 0; i < 81; ++i){
		    if(board[i / 9][ i % 9 ] == ‘.‘)
				blankCells.add(i);
		}
		dfs(board, 0, blankCells);
    }
	
	private boolean dfs(char[][] board, int start, List<Integer> blankCells) {
		if(start == blankCells.size()) return true; //dfs reaches the end
		//get the coordinates of the cell to be filled
		int currentCoordinate = blankCells.get(start);
		int row = currentCoordinate / 9;
		int column = currentCoordinate % 9;
		//fill a number in the cell
		for(int num = 1; num < 10; ++num) {
			//check the sudoku is valid after being filled num
			if(isValid(num, board,row,column)) {
				board[row][column] = (char)(num + ‘0‘);
				if(dfs(board,start + 1, blankCells))
					return true;
				//if a solution can not be reached after the filling, we need to erase the filling for next try
				board[row][column] = ‘.‘;
			}
		}
		return false;
	}
	
	private boolean isValid(int num, char[][] board, int row, int column) {
		//check whether num is in the row, column and grid
		for(int i = 0; i < 9; ++i){
			if(board[row][i] -‘0‘ == num) return false; //row 
			if(board[i][column] - ‘0‘ == num) return false; //column
			if(board[3 *(row / 3) + i / 3][3 * (column / 3) + i % 3] - ‘0‘ == num) return false;
		}
		return true;
    }
}

  

leetcode--Sudoku Solver,布布扣,bubuko.com

leetcode--Sudoku Solver

标签:blog   http   java   art   for   io   

原文地址:http://www.cnblogs.com/averillzheng/p/3825376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!