Skip to content

Commit f682fff

Browse files
author
applewjg
committed
SudokuSolver.java
Change-Id: Iaf6e0b59a929f642abd17747f49e458545f908ac
1 parent 8688eac commit f682fff

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

SudokuSolver.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 20, 2014
4+
Problem: Sudoku Solver
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/sudoku-solver/
7+
Notes:
8+
Write a program to solve a Sudoku puzzle by filling the empty cells.
9+
Empty cells are indicated by the character '.'.
10+
You may assume that there will be only one unique solution.
11+
12+
Solution: back-tracking..
13+
*/
14+
public class Solution {
15+
public void solveSudoku(char[][] board) {
16+
solve(board);
17+
}
18+
boolean solve(char[][] board){
19+
for(int i = 0;i<9;i++){
20+
for(int j=0;j<9;j++){
21+
if(board[i][j]=='.'){
22+
for(char ch = '1';ch<='9';ch++){
23+
board[i][j]=ch;
24+
if(isValidSudoKu(board,i,j)&&solve(board)) return true;
25+
board[i][j]='.';
26+
}
27+
return false;
28+
}
29+
}
30+
}
31+
return true;
32+
}
33+
boolean isValidSudoKu(char[][] board, int x, int y){
34+
for(int i = 0; i<9; i++){
35+
if(i!=y&&board[x][i]==board[x][y]) return false;
36+
}
37+
for(int i=0;i<9;i++){
38+
if(i!=x&&board[i][y]==board[x][y]) return false;
39+
}
40+
for(int i=3*(x/3);i<3*(x/3)+3;i++){
41+
for(int j=3*(y/3);j<3*(y/3)+3;j++){
42+
if(i!=x&&j!=y&&board[i][j]==board[x][y]) return false;
43+
}
44+
}
45+
return true;
46+
}
47+
}

0 commit comments

Comments
 (0)