FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/PuzzleCoding/src/SpiralMatrix.java at master · wodgithub/algorithm · GitHub
wodgithub
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
SpiralMatrix.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (43 loc) · 1.22 KB
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
SpiralMatrix.java
Copy path
File metadata and controls
47 lines (43 loc) · 1.22 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
java
.
util
.
Arrays
;
/**
* Given an integer n,
* generate a square matrix filled with elements from 1 to n2 in spiral order.
* <p/>
* For example,
* Given n = 3,
* <p/>
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*/
public
class
SpiralMatrix
{
public
static
void
main
(
String
[]
args
) {
int
N
=
4
;
int
[][]
spiralMatrix
=
spiralMatrix
(
N
);
for
(
int
i
=
0
;
i
<
spiralMatrix
.
length
; ++
i
)
System
.
out
.
println
(
Arrays
.
toString
(
spiralMatrix
[
i
]));
}
public
static
int
[][]
spiralMatrix
(
int
n
) {
int
[][]
matrix
=
new
int
[
n
][
n
];
int
m
=
n
-
1
;
int
k
=
0
;
for
(
int
layer
=
0
;
layer
<=
m
/
2
; ++
layer
) {
//top
for
(
int
j
=
layer
;
j
<=
m
-
layer
; ++
j
)
matrix
[
layer
][
j
] = ++
k
;
//right
for
(
int
i
=
layer
+
1
;
i
<=
m
-
layer
; ++
i
)
matrix
[
i
][
m
-
layer
] = ++
k
;
//bottom
for
(
int
j
=
m
-
layer
-
1
;
j
>=
layer
; --
j
)
matrix
[
m
-
layer
][
j
] = ++
k
;
//left
for
(
int
i
=
m
-
layer
-
1
;
i
>=
layer
+
1
; --
i
)
matrix
[
i
][
layer
] = ++
k
;
}
return
matrix
;
}
}
Back
|
FazBrowse Home
|
New Git URL