59. Spiral Matrix II Medium
1/**
2 * [59] Spiral Matrix II
3 *
4 * Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
5 *
6 * Example 1:
7 * <img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" style="width: 242px; height: 242px;" />
8 * Input: n = 3
9 * Output: [[1,2,3],[8,9,4],[7,6,5]]
10 *
11 * Example 2:
12 *
13 * Input: n = 1
14 * Output: [[1]]
15 *
16 *
17 * Constraints:
18 *
19 * 1 <= n <= 20
20 *
21 */
22pub struct Solution {}
23
24// problem: https://leetcode.com/problems/spiral-matrix-ii/
25// discuss: https://leetcode.com/problems/spiral-matrix-ii/discuss/?currentPage=1&orderBy=most_votes&query=
26
27// submission codes start here
28
29impl Solution {
30 pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
31 let mut result = vec![vec![0; n as usize]; n as usize];
32
33 let mut top = 0;
34 let mut bottom = n as usize - 1;
35 let mut left = 0;
36 let mut right = n as usize - 1;
37 let mut current = 1;
38
39 while current <= n * n {
40 for i in left..right + 1 {
41 result[top][i] = current;
42 current += 1;
43 }
44 top += 1;
45 for i in top..bottom + 1 {
46 result[i][right] = current;
47 current += 1;
48 }
49 if right == 0 {
50 break;
51 }
52 right -= 1;
53 for i in (left..right + 1).rev() {
54 result[bottom][i] = current;
55 current += 1;
56 }
57 if bottom == 0 {
58 break;
59 }
60 bottom -= 1;
61 for i in (top..bottom + 1).rev() {
62 result[i][left] = current;
63 current += 1;
64 }
65 left += 1;
66 }
67
68 result
69 }
70}
71
72// submission codes end
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn test_59() {
80 let x = Solution::generate_matrix(3);
81 println!("Got {:#?}", x);
82 }
83}
84
Back
© 2025 bowen.ge All Rights Reserved.