zoukankan      html  css  js  c++  java
  • 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.

     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 }
  • 相关阅读:
    java.lang.OutOfMemoryError: Java heap space解决方法
    深入理解SQL的四种连接-左外连接、右外连接、内连接、全连接
    CSS中.和#区别
    斯坦福数据挖掘之LSH的应用
    N个元素的集合划分成互斥的两个子集的数目
    JDBC小结
    初识Java反射机制
    关于Java中重载的若干问题
    吐槽
    Tomcat
  • 原文地址:https://www.cnblogs.com/birdhack/p/4268852.html
Copyright © 2011-2022 走看看