LeetCode | 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.

分析

遞歸的方法,根據數獨規則剪枝。

代碼

public class SudokuSolver {
	int N;
	int subSize;
	char[][] board;

	public void solveSudoku(char[][] board) {
		this.board = board;
		N = board.length;
		subSize = (int) Math.sqrt(N);
		solve(0);
	}

	private boolean solve(int index) {
		if (index == N * N) {
			return true;
		}
		int x = index / N;
		int y = index % N;
		if (board[x][y] == '.') {
			for (char c = '1'; c <= '9'; ++c) {
				if (isValidCell(x, y, c)) {
					board[x][y] = c;
					if (solve(index + 1)) {
						return true;
					}
					board[x][y] = '.';
				}
			}
		} else {
			return solve(index + 1);
		}
		return false;
	}

	private boolean isValidCell(int x, int y, char c) {
		// row
		for (int column = 0; column < N; ++column) {
			if (board[x][column] == c) {
				return false;
			}
		}

		// column
		for (int row = 0; row < N; ++row) {
			if (board[row][y] == c) {
				return false;
			}
		}

		// subboard
		int originRow = (x / subSize) * subSize;
		int originColumn = (y / subSize) * subSize;
		for (int i = 0; i < N; ++i) {
			int row = originRow + i / subSize;
			int column = originColumn + i % subSize;
			if (board[row][column] == c) {
				return false;
			}
		}
		return true;
	}
}
發佈了152 篇原創文章 · 獲贊 125 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章