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

LeetCode 36 Sudoku Solver

时间:2015-07-09 12:41:17      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路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

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4632527.html

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