Skip to main content
Back to problems
#2326
Medium Algorithms

Spiral matrix iv

Array Linked List Matrix Simulation
82.3% acceptance
Feb 25, 2026
1315
56
You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers. Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. Fill remaining empty spaces with -1. Return the generated matrix.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn spiral_matrix(m: i32, n: i32, head: Option<Box<ListNode>>) -> Vec<Vec<i32>> {
    let (m, n) = (m as usize, n as usize);
    let mut matrix = vec![vec![-1i32; n]; m];

    let mut vals = vec![];
    let mut node = head;
    while let Some(nd) = node {
      vals.push(nd.val);
      node = nd.next;
    }

    let (mut top, mut bottom, mut left, mut right) = (0i32, m as i32 - 1, 0i32, n as i32 - 1);
    let mut idx = 0usize;

    while top <= bottom && left <= right && idx < vals.len() {
      for c in left..=right {
        if idx >= vals.len() { break; }
        matrix[top as usize][c as usize] = vals[idx];
        idx += 1;
      }
      top += 1;
      for r in top..=bottom {
        if idx >= vals.len() { break; }
        matrix[r as usize][right as usize] = vals[idx];
        idx += 1;
      }
      right -= 1;
      if top <= bottom {
        for c in (left..=right).rev() {
          if idx >= vals.len() { break; }
          matrix[bottom as usize][c as usize] = vals[idx];
          idx += 1;
        }
        bottom -= 1;
      }
      if left <= right {
        for r in (top..=bottom).rev() {
          if idx >= vals.len() { break; }
          matrix[r as usize][left as usize] = vals[idx];
          idx += 1;
        }
        left += 1;
      }
    }

    matrix
  }
}