 思路:模拟遍历的过程,每次访问的正好是按螺旋顺序应该访问的元素,共访问 m* n次
function spiralOrder($matrix) {
$rows = count($matrix);
$cols = count($matrix[0]);
if ($rows == 0 || $cols == 0) {
return [];
}
$count = $rows * $cols;
$visited = array_fill(0, $rows*$cols, false);
$direction = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
$dirIndex = 0;
$r = 0;
$c = 0;
$_R = [];
while ($count-- > 0) {
$index = $r * $cols + $c;
$visited[$index] = true;
$_R[] = $matrix[$r][$c];
$r_new = $r + $direction[$dirIndex][0];
$c_new = $c + $direction[$dirIndex][1];
if ($r_new > $rows - 1 || $r_new < 0 || $c_new > $cols - 1 || $c_new < 0 || $visited[$r_new*$cols+$c_new]) {
$dirIndex = ($dirIndex + 1) % 4;
}
$r = $r + $direction[$dirIndex][0];
$c = $c + $direction[$dirIndex][1];
}
return $_R;
}
|