数独解题PHP工具类

定义sudoUtils类

<?php
namespace app\common\utils;
class SudoUtils
{
    private $sudoArr;
    public function __construct($sudoArr) {
        $this->sudoArr = $sudoArr;
    }
    public function solveSudoku() {
        $row = 0;
        $col = 0;
        if (!$this->findEmptyCell($row, $col)) {
            return true; // 数独已经解决
        }
        for ($num = 1; $num <= 9; $num++) {
            if ($this->isSafe($row, $col, $num)) {
                $this->sudoArr[$row][$col] = $num;
                if ($this->solveSudoku()) {

                    echo '行数:'.$row.'列数:'.$col.'值为:'.$num.'<br/>';
                    return true;
                }
                $this->sudoArr[$row][$col] = 0; // 回溯
            }
        }
        return false; // 无解
    }
    private function findEmptyCell(&$row, &$col) {
        for ($row = 0; $row < 9; $row++) {
            for ($col = 0; $col < 9; $col++) {
                if ($this->sudoArr[$row][$col] == 0) {
                    return true; // 找到一个空单元格
                }
            }
        }
        return false; // 数独已经填满
    }
    private function isSafe($row, $col, $num) {
        return !$this->usedInRow($row, $num) && !$this->usedInCol($col, $num) && !$this->usedInBox($row - $row % 3, $col - $col % 3, $num);
    }
    private function usedInRow($row, $num) {
        for ($col = 0; $col < 9; $col++) {
            if ($this->sudoArr[$row][$col] == $num) {
                return true; // 数字已经在行中存在
            }
        }
        return false;
    }
    private function usedInCol($col, $num) {
        for ($row = 0; $row < 9; $row++) {
            if ($this->sudoArr[$row][$col] == $num) {
                return true; // 数字已经在列中存在
            }
        }
        return false;
    }
    private function usedInBox(int $boxStartRow,int $boxStartCol, int $num):bool{
        for ($row = 0; $row < 3; $row++) {
            for ($col = 0; $col < 3; $col++) {
                if ($this->sudoArr[$row + $boxStartRow][$col + $boxStartCol] == $num) {
                    return true;
                }
            }
        }
        return false;
    }
    public function printsudoArr() {
        return $this->sudoArr;

    }

}

评论

(= ̄ω ̄=)··· 暂无内容!

回复

您还未登录,请先登录或者注册