0054.螺旋矩阵

方法一:按层模拟

时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$,mn 表示输入矩阵的行数和列数。

func spiralOrder(matrix [][]int) []int {
	ans := []int{}
	top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1
	for top <= bottom && left <= right {
		for i := left; i <= right; i++ {
			ans = append(ans, matrix[top][i])
		}
		top += 1
		for i := top; i <= bottom; i++ {
			ans = append(ans, matrix[i][right])
		}
		right -= 1
		if top > bottom || left > right {
			break
		}
		for i := right; i >= left; i-- {
			ans = append(ans, matrix[bottom][i])
		}
		bottom -= 1
		for i := bottom; i >= top; i-- {
			ans = append(ans, matrix[i][left])
		}
		left += 1
	}
	return ans
}
impl Solution {
    pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
        let (mut i, mut j, mut m, mut n) = (0, 0, matrix.len(), matrix[0].len());
        let mut ans = Vec::new();
        while i < m && j < n {
            for y in j..n {
                ans.push(matrix[i][y]);
            }
            i += 1;
            for x in i..m {
                ans.push(matrix[x][n - 1]);
            }
            n -= 1;
            if i >= m || j >= n {
                break;
            }
            for y in (j..n).rev() {
                ans.push(matrix[m - 1][y]);
            }
            m -= 1;
            for x in (i..m).rev() {
                ans.push(matrix[x][j]);
            }
            j += 1;
        }
        ans
    }
}