54. Spiral Matrix

Description of Problem

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Solution

Tags: Divide and Conquer

Explanation

The same manner as 59. Spiral Matrix II. However, we must consider 4 base cases at the end.

Code

impl Solution {
    pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
        let mut m = matrix.len();
        let mut n = matrix[0].len();
        let mut row = 0;
        let mut col = 0;
        let mut v = vec![];
        
        while m > 1 && n > 1 {
            Solution::fill1(&matrix, &mut v, row, col, m, n);
            Solution::fill2(&matrix, &mut v, row, col, m, n);
            Solution::fill3(&matrix, &mut v, row, col, m, n);
            Solution::fill4(&matrix, &mut v, row, col, m, n);
            row+=1; col+=1;
            m-=2; n-=2;
        }
        
        let mut i = 0; 
        while m > 1 && n == 1 && i < m {
            v.push(matrix[row+i][col]);
            i+=1;
        }
        
        let mut j = 0; 
        while n > 1 && m == 1 && j < n {
            v.push(matrix[row][col+j]);
            j+=1;
        }

        if m == 1 && n == 1{
            v.push(matrix[row][col]);
        }
        
        return v;
    }
    
    fn fill1(
        matrix : &Vec<Vec<i32>>, 
        v: &mut Vec<i32>,
        row: usize, 
        col: usize, 
        m: usize,
        n: usize
    ) {
        for j in 0..=(n-2) {
            v.push(matrix[row][col+j]);
        }
    }

    fn fill2(
        matrix : &Vec<Vec<i32>>, 
        v: &mut Vec<i32>,
        row: usize, 
        col: usize, 
        m: usize,
        n: usize
    ) {
        for i in 0..=(m-2) {
            v.push(matrix[row+i][col+n-1]);
        }
    }

    fn fill3(
        matrix : &Vec<Vec<i32>>, 
        v: &mut Vec<i32>,
        row: usize, 
        col: usize, 
        m: usize,
        n: usize
    ) {
        for j in (1..=(n-1)).rev() {
            v.push(matrix[row + m -1][col+j]);
        }
    }

    fn fill4(
        matrix : &Vec<Vec<i32>>, 
        v: &mut Vec<i32>,
        row: usize, 
        col: usize, 
        m: usize,
        n: usize
    ) {
        for i in (1..=(m-1)).rev() {
            v.push(matrix[row + i][col]);
        }
    }
}