-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
98 lines (89 loc) · 1.56 KB
/
main.go
File metadata and controls
98 lines (89 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Source: https://leetcode.com/problems/spiral-matrix-ii
// Title: Spiral Matrix II
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
//
// Example 1:
//
// https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
//
// Input: n = 3
// Output: [[1,2,3],[8,9,4],[7,6,5]]
//
// Example 2:
//
// Input: n = 1
// Output: [[1]]
//
// Constraints:
//
// 1 <= n <= 20
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
func generateMatrix(n int) [][]int {
matrix := make([][]int, n)
for i := 0; i < n; i++ {
matrix[i] = make([]int, n)
}
// boundaries
north := 0
south := n - 1
west := 0
east := n - 1
// spiral
i := 1
for true {
// Right
if west > east {
break
}
{
y := north
for x := west; x <= east; x++ {
matrix[y][x] = i
i++
}
north++
}
// Down
if north > south {
break
}
{
x := east
for y := north; y <= south; y++ {
matrix[y][x] = i
i++
}
east--
}
// Left
if west > east {
break
}
{
y := south
for x := east; x >= west; x-- {
matrix[y][x] = i
i++
}
south--
}
// Up
if north > south {
break
}
{
x := west
for y := south; y >= north; y-- {
matrix[y][x] = i
i++
}
west++
}
}
return matrix
}