From e8851b049069734f3f7c8b03ef5c8a2e698dd25b Mon Sep 17 00:00:00 2001 From: nolanzzz Date: Wed, 1 Sep 2021 19:08:21 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200059.=E8=9E=BA=E6=97=8B?= =?UTF-8?q?=E7=9F=A9=E9=98=B5II=20PHP=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 4231fb39..3dbc2a50 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -426,6 +426,48 @@ impl Solution { } ``` +PHP: +```php +class Solution { + /** + * @param Integer $n + * @return Integer[][] + */ + function generateMatrix($n) { + // 初始化数组 + $res = array_fill(0, $n, array_fill(0, $n, 0)); + $mid = $loop = floor($n / 2); + $startX = $startY = 0; + $offset = 1; + $count = 1; + while ($loop > 0) { + $i = $startX; + $j = $startY; + for (; $j < $startY + $n - $offset; $j++) { + $res[$i][$j] = $count++; + } + for (; $i < $startX + $n - $offset; $i++) { + $res[$i][$j] = $count++; + } + for (; $j > $startY; $j--) { + $res[$i][$j] = $count++; + } + for (; $i > $startX; $i--) { + $res[$i][$j] = $count++; + } + $startX += 1; + $startY += 1; + $offset += 2; + $loop--; + } + if ($n % 2 == 1) { + $res[$mid][$mid] = $count; + } + return $res; + } +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)