<?php
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
function spiralOrder( $matrix )
{
// write code here
$count = count($matrix);//行数
if(empty($count)) return $matrix;
$array = [];
$top = $left = 0; //从左上角开始
$bottom = $count-1; //获取最底层行的键值
$right = count($matrix[0])-1;//获取第一行最右侧键值
while($top <= $bottom && $left <= $right){
//从左向右 1->3
for($i=$left;$i<=$right;$i++){
// 把第一行加入数组
array_push($array,$matrix[$top][$i]);
}
//从上到下 6->9
for($i=$top+1;$i<=$bottom;$i++){ //$top+1 刨去3
//把每行最右侧的值加入数组
array_push($array,$matrix[$i][$right]);
}
//从右到左 8->7
for($i=$right-1;$top!=$bottom && $i>=$left;$i--){ //$right-1 刨去9;
//把最后一行的值加入数组
array_push($array,$matrix[$bottom][$i]);
}
//从下到上 4->5
for($i=$bottom-1;$left!=$right && $i >=$top+1;$i--){ //$bottom-1 从下往上 刨去7;$top+1 固定第二行;$left!=$right 刨去6
//从左侧开始 把4和5加入数组
array_push($array,$matrix[$i][$left]);
}
//每循环一圈 向内层逼近
++$left;
++$top;
--$right;
--$bottom;
}
return $array;
}
螺旋输出矩阵
最新推荐文章于 2023-03-22 20:03:51 发布