|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** |
4 |
| - * 59. Spiral Matrix II |
5 |
| - * |
6 |
| - * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. |
7 |
| -
|
8 |
| - For example, |
9 |
| - Given n = 3, |
10 |
| -
|
11 |
| - You should return the following matrix: |
12 |
| - [ |
13 |
| - [ 1, 2, 3 ], |
14 |
| - [ 8, 9, 4 ], |
15 |
| - [ 7, 6, 5 ] |
16 |
| - ] |
17 |
| - */ |
18 | 3 | public class _59 {
|
19 | 4 |
|
20 |
| - public static class Solution1 { |
21 |
| - /**credit: https://leetcode.com/problems/spiral-matrix-ii/discuss/22289/My-Super-Simple-Solution.-Can-be-used-for-both-Spiral-Matrix-I-and-II/21907*/ |
22 |
| - public int[][] generateMatrix(int n) { |
23 |
| - int[][] matrix = new int[n][n]; |
24 |
| - if (n == 0) { |
25 |
| - return matrix; |
26 |
| - } |
27 |
| - int value = 1; |
28 |
| - int top = 0; |
29 |
| - int bottom = n - 1; |
30 |
| - int left = 0; |
31 |
| - int right = n - 1; |
32 |
| - while (left <= right && top <= bottom) { |
33 |
| - for (int j = left; j <= right; j++) { |
34 |
| - matrix[top][j] = value++; |
35 |
| - } |
36 |
| - top++; |
37 |
| - for (int i = top; i <= bottom; i++) { |
38 |
| - matrix[i][right] = value++; |
39 |
| - } |
40 |
| - right--; |
41 |
| - for (int j = right; j >= left; j--) { |
42 |
| - matrix[bottom][j] = value++; |
43 |
| - } |
44 |
| - bottom--; |
45 |
| - for (int i = bottom; i >= top; i--) { |
46 |
| - matrix[i][left] = value++; |
| 5 | + public static class Solution1 { |
| 6 | + /** |
| 7 | + * credit: https://leetcode.com/problems/spiral-matrix-ii/discuss/22289/My-Super-Simple-Solution.-Can-be-used-for-both-Spiral-Matrix-I-and-II/21907 |
| 8 | + */ |
| 9 | + public int[][] generateMatrix(int n) { |
| 10 | + int[][] matrix = new int[n][n]; |
| 11 | + if (n == 0) { |
| 12 | + return matrix; |
| 13 | + } |
| 14 | + int value = 1; |
| 15 | + int top = 0; |
| 16 | + int bottom = n - 1; |
| 17 | + int left = 0; |
| 18 | + int right = n - 1; |
| 19 | + while (left <= right && top <= bottom) { |
| 20 | + for (int j = left; j <= right; j++) { |
| 21 | + matrix[top][j] = value++; |
| 22 | + } |
| 23 | + top++; |
| 24 | + for (int i = top; i <= bottom; i++) { |
| 25 | + matrix[i][right] = value++; |
| 26 | + } |
| 27 | + right--; |
| 28 | + for (int j = right; j >= left; j--) { |
| 29 | + matrix[bottom][j] = value++; |
| 30 | + } |
| 31 | + bottom--; |
| 32 | + for (int i = bottom; i >= top; i--) { |
| 33 | + matrix[i][left] = value++; |
| 34 | + } |
| 35 | + left++; |
| 36 | + } |
| 37 | + return matrix; |
47 | 38 | }
|
48 |
| - left++; |
49 |
| - } |
50 |
| - return matrix; |
51 | 39 | }
|
52 |
| - } |
53 | 40 | }
|
0 commit comments