题意:
解题思路:
思路:
1.从左到右,从上到下,从右到左,从下到上依次遍历每一个数
2.时间复杂度:O(n),每个元素遍历一次
PHP代码实现:
class Solution {
/**
* @param Integer[][] $matrix
* @return Integer[]
*/
function spiralOrder($matrix) {
$ret = [];
if (count($matrix) == 0 || count($matrix[0]) == 0) return $ret;
$top = 0; $bottom = count($matrix) - 1;
$left = 0; $right = count($matrix[0]) - 1;
while (true) {
//from left to right
for ($i = $left; $i <= $right; $i++) {
array_push($ret, $matrix[$top][$i]);
}
$top++;
if ($left > $right || $top > $bottom) break;
//from top to bottom
for ($i = $top; $i <= $bottom; $i++) {
array_push($ret, $matrix[$i][$right]);
}
$right--;
if ($left > $right || $top > $bottom) break;
//from right to left
for ($i = $right; $i >= $left; $i--) {
array_push($ret, $matrix[$bottom][$i]);
}
$bottom--;
if ($left > $right || $top > $bottom) break;
//from bottom to top
for ($i = $bottom; $i >= $top; $i--) {
array_push($ret, $matrix[$i][$left]);
}
$left++;
if ($left > $right || $top > $bottom) break;
}
return $ret;
}
}
GO代码实现:
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return nil
}
step := 0
size := len(matrix) * len(matrix[0])
top, bottom, left, right := 0, len(matrix) - 1, 0, len(matrix[0]) - 1
result := make([]int, size)
for step < size {
for i := left; i <= right && step < size; i++ {
result[step] = matrix[top][i]
step++
}
top++
for i := top; i <= bottom && step < size; i++ {
result[step] = matrix[i][right]
step++
}
right--
for i := right; i >= left && step < size; i-- {
result[step] = matrix[bottom][i]
step++
}
bottom--
for i := bottom; i >= top && step < size; i-- {
result[step] = matrix[i][left]
step++
}
left++
}
return result
}