LeetCode—sudoku-solver(数独的解法)—java

题目描述

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.

LeetCode—sudoku-solver(数独的解法)—java_第1张图片

A sudoku puzzle...


LeetCode—sudoku-solver(数独的解法)—java_第2张图片

...and its solution numbers marked in red.

思路解析

  • 回溯法,从一条路往前走,能进则进,不能进就后退,换一条路
  • 这个问题的解决方法也是一样的,需要从‘1’到‘9’填数字,满足直接返回true;不满足就回退到‘.’
  • 遍历每一行,每一列,只要是‘.’的,就要尝试填入‘1’到‘9’
  • 注意判断是否是空的条件,首先判断行,i;然后判断列,j;然后判断每个小block是否合法。都判断完毕,就是真正的答案了。

代码

public class Solution {
    public void solveSudoku(char[][] board) {
        if(board == null||board.length==0)
            return ;
        helper(board);
    }
    private boolean helper(char[][] board){
        for(int i=0;i

你可能感兴趣的:(牛客,Java,在线编程,数组,LeetCode,数独)