首页 > 其他 > 详细

LeetCode Sudoku Solver

时间:2015-02-02 22:47:32      阅读:273      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!