码迷,mamicode.com
首页 > Web开发 > 详细

37. Sudoku Solver(js)

时间:2019-02-21 21:37:51      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:棋盘   png   modify   ali   not   func   solution   svg   col   

37. Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3sub-boxes of the grid.

Empty cells are indicated by the character ‘.‘.

技术图片
A sudoku puzzle...

技术图片

题意:填满剩余数字,使其满足数独

代码如下:

/**
 * @param {character[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var solveSudoku = function(board) {
    if(board.length===0 || board.length!==9 || board[0].length!==9) return ;
    dfs(board,0,0);
};
// 判断是否符合要求
/**
*1.每一行值各不相同
*2.每一列值各不相同
*3.每个3X3的小棋盘里的值各不相同
*/
var isValid=function(board,i,j){
    for(let col=0;col<9;col++){
        if(col!==j && board[i][j]===board[i][col]) return false;
    }
    for(let row=0;row<9;row++){
        if(row!==i && board[i][j]===board[row][j]) return false;
    }
    for(let row=parseInt(i/3)*3;row<parseInt(i/3)*3+3;row++){
        for(let col=parseInt(j/3)*3;col<parseInt(j/3)*3+3;col++){
            if((row!==i || col!==j)&&board[i][j]===board[row][col]) return false;
        }
    }
    return true;
};
/**
*递归遍历,边界判断,逐个数字带入值为‘.‘的方格,判断其是否符合要求
*/
var  dfs=function(board,i,j){
    if(i===9) return true;
    if(j>=9) return dfs(board,i+1,0);
    if(board[i][j]===‘.‘){
        for(let k=1;k<=9;k++){
            board[i][j]=k+‘‘;
            if(isValid(board,i,j)){
                if(dfs(board,i,j+1)) return true;
            }
            board[i][j]=‘.‘;
        }
    }else{
        return dfs(board,i,j+1);
    }
    return false;
};

 

37. Sudoku Solver(js)

标签:棋盘   png   modify   ali   not   func   solution   svg   col   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10415253.html

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