Sudoku Solver - Leetcode

本文介绍了一种用于填充空白单元格以解决数独谜题的算法。该算法逐个遍历空单元格,尝试将1-9的数字填入,并确保不违反数独规则。通过递归调用自身,算法能够找到唯一解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Solution {
    public void solveSudoku(char[][] board) {
        solveSudokuHelper(board);
    }
    private boolean solveSudokuHelper(char[][] board){
        for(int i=0; i<board.length; i++)
         for(int j=0; j<board.length; j++){
             if(board[i][j] == '.'){
                 for(char k='1'; k<='9'; k++){
                     board[i][j] = k;
                      if(isValidSudoku(board,i,j) && solveSudokuHelper(board))
	                     return true;
                     board[i][j]='.';    
                 }
                 return false;
             }
         }
         return true;
    }
    
    private boolean isValidSudoku(char[][] board, int x, int y){
        for(int j=0; j<board.length; j++){
            if(j!=y && board[x][j]==board[x][y])
                return false;
        }
        for(int i=0; i<board.length; i++){
            if(i!=x && board[i][y]==board[x][y])
                return false;
        }
        for(int i=3*(x/3); i<3*(x/3)+3 ; i++)
          for(int j=3*(y/3); j<3*(y/3)+3; j++)
          {
              if(<span style="background-color: rgb(255, 255, 51);">(i!=x||j!=y)</span> && board[i][j]==board[x][y])
                  return false;
          }
        return true;  
    }
    
}



分析:每遇到一个空格,验证【1-9】的每一个数字,如果该数字使得bord没有破坏数独的规律(横、竖、九宫)同时 通过该数字深度验证下一个空格的可能值

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值