From 01f734bc8697cf115b567a1ef62a7deca875d01f Mon Sep 17 00:00:00 2001 From: yangmin Date: Wed, 23 Jan 2019 14:40:30 +0800 Subject: [PATCH] backtracking 8queens --- php/39_backtracking/queens.php | 74 ++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 php/39_backtracking/queens.php diff --git a/php/39_backtracking/queens.php b/php/39_backtracking/queens.php new file mode 100644 index 0000000..de99eef --- /dev/null +++ b/php/39_backtracking/queens.php @@ -0,0 +1,74 @@ +printQueens(); + return; + } + + //每一行有8中放法 + for($column = 0; $column < 8; $column++) { + if ($this->isOk($row, $column)) { + $this->result[$row] = $column; + $this->cal8queens($row + 1); + } + } + } + + //row行的column列是否合适 + function isOk($row, $column) + { + $leftup = $column - 1; + $rightdown = $column + 1; + + for ($i = $row - 1; $i >= 0; $i--) { + //判断上一行的 column 列是否有值 + if ($this->result[$i] == $column) { + return false; + } + + //左上角是否有值 + if ($leftup >= 0 && $this->result[$i] == $leftup) { + return false; + } + + //右下角是否有值 + if ($rightdown < 8 && $this->result[$i] == $rightdown) { + return false; + } + + $leftup--; + $rightdown++; + + } + + return true; + } + + //打印 + function printQueens() + { + for ($row = 0; $row < 8; $row++) { + for ($column = 0; $column < 8; $column++) { + if ($this->result[$row] == $column) { + echo 'Q'; + } else { + echo '*'; + } + } + echo '
'; + } + } +} + +$queen = new Queen(); +$queen->cal8queens(0);