Java [leetcode 37]Sudoku Solver

题目描述:

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.

解题思路:

本题使用回溯和HashSet的方法。对于每一个空白位置,试探的使用‘1’-'9’之间的数字,如果加入该数字在满足数独规则的情况下,将该字符加入该位置,向下去试探;如果试探失败,则回到当前这步,换另一个字符继续进行试探。

代码如下:

public class Solution {
    public void solveSudoku(char[][] board) {
		HashSet[] row = new HashSet[9];
		HashSet[] col = new HashSet[9];
		HashSet[] cell = new HashSet[9];
		initHashSet(board, row, col, cell);
		solve(board, row, col, cell);
	}

	public boolean solve(char[][] board, HashSet[] row, HashSet[] col,
			HashSet[] cell) {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				if (board[i][j] == '.') {
					for (char c = '1'; c <= '9'; c++) {
						if (isValidSudoku(board, i, j, c, row, col, cell)) {
							board[i][j] = c;
							row[i].add(c);
							col[j].add(c);
							cell[3 * (i / 3) + j / 3].add(c);
							if (solve(board, row, col, cell))
								return true;
							else {
								board[i][j] = '.';
								row[i].remove(c);
								col[j].remove(c);
								cell[3 * (i / 3) + j / 3].remove(c);
							}
						}
					}
					return false;
				}
			}
		}
		return true;
	}

	public boolean isValidSudoku(char[][] board, int i, int j, char c,
			HashSet[] row, HashSet[] col, HashSet[] cell) {
		if (row[i].contains(c) || col[j].contains(c)
				|| cell[3 * (i / 3) + j / 3].contains(c))
			return false;
		return true;

	}

	public void initHashSet(char[][] board, HashSet[] row,
			HashSet[] col, HashSet[] cell) {
		for (int i = 0; i < 9; i++) {
			row[i] = new HashSet<Character>();
			col[i] = new HashSet<Character>();
			cell[i] = new HashSet<Character>();
		}
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				if (board[i][j] != '.') {
					row[i].add(board[i][j]);
					col[j].add(board[i][j]);
					cell[3 * (i / 3) + j / 3].add(board[i][j]);
				}
			}
		}
	}
}
原文地址:https://www.cnblogs.com/zihaowang/p/4970069.html