Leetcode 36 Sudoku Solver

Source: Internet
Author: User

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.

Idea 1: use violent 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);}}
Idea 2: Use dancing links to complete the code.


Leetcode 36 Sudoku Solver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.