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

LeetCode Sudoku Solver

时间:2015-02-02 22:49:09      阅读:234      评论: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 public class Solution {
 2 
 3      public void solveSudoku(char[][] board) {
 4          doSolveSudoku(board);
 5      }
 6      private boolean doSolveSudoku(char[][] board) {
 7          for (int i = 0; i < 9; i++) {
 8              for (int j = 0; j < 9; j++) {
 9                  if (‘.‘ == board[i][j]) {
10                      for (int k = 1; k <= 9; k++) {
11                          board[i][j] = (char) (‘0‘ + k);
12                          if (isValid(board, i, j)) {
13                              if (doSolveSudoku(board)) {
14                                  return true;
15                              }
16                          }
17                          board[i][j]=‘.‘;
18                      }
19                      return false;
20                  }
21              }
22          }
23          return true;
24      }
25      private boolean isValid(char[][] board, int x, int y) {
26          int row,col;
27          for (row = 0; row < 9; row++) {
28              if ((x != row) && (board[row][y] == board[x][y])) {
29                  return false;
30              }
31          }
32          for (col = 0; col < 9; col++) {
33              if ((y != col) && (board[x][y] == board[x][col])) {
34                  return false;
35              }
36          }
37          for (row = (x/3)*3; row <(x/3+1)*3 ; row++) {
38              for (col = (y/3)*3; col <(y/3+1)*3 ; col++) {
39                  if ((x != row) && (y != col) && (board[x][y] == board[row][col])) {
40                      return false;
41                  }
42              }
43          }
44          return true;
45      }
46 }

 

LeetCode Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4268852.html

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