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

LeetCode 36 Sudoku Solver

时间:2014-11-01 21:52:53      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

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.

思路1:使用暴力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 (board[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);
	}
}
思路2:使用Dancing Links,代码后补。


LeetCode 36 Sudoku Solver

标签:java   leetcode   

原文地址:http://blog.csdn.net/mlweixiao/article/details/40684827

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