Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitca4eeb5

Browse files
author
applewjg
committed
SpiralMatrix
Change-Id: I286067954e3c6fe23dde7538a004bae96c810920
1 parent69b90ab commitca4eeb5

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

‎SpiralMatrix.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 25, 2014
4+
Problem: Spiral Matrix
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/spiral-matrix/
7+
Notes:
8+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
9+
For example,
10+
Given the following matrix:
11+
[
12+
[ 1, 2, 3 ],
13+
[ 4, 5, 6 ],
14+
[ 7, 8, 9 ]
15+
]
16+
You should return [1,2,3,6,9,8,7,4,5].
17+
18+
Solution: ...
19+
*/
20+
publicclassSolution {
21+
publicList<Integer>spiralOrder(int[][]matrix) {
22+
ArrayList<Integer>res =newArrayList<Integer>();
23+
if (matrix.length ==0 ||matrix[0].length ==0)returnres;
24+
intn =matrix.length,m =matrix[0].length,row =0,col = -1;
25+
while (true) {
26+
for (inti =0;i <m; ++i)res.add(matrix[row][++col]);
27+
if (--n ==0)break;
28+
for (inti =0;i <n; ++i)res.add(matrix[++row][col]);
29+
if (--m ==0)break;
30+
for (inti =0;i <m; ++i)res.add(matrix[row][--col]);
31+
if (--n ==0)break;
32+
for (inti =0;i <n; ++i)res.add(matrix[--row][col]);
33+
if (--m ==0)break;
34+
}
35+
returnres;
36+
}
37+
}

‎SpiralMatrixII.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 25, 2014
4+
Problem: Spiral Matrix II
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/spiral-matrix-ii/
7+
Notes:
8+
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
9+
For example,
10+
Given n = 3,
11+
You should return the following matrix:
12+
[
13+
[ 1, 2, 3 ],
14+
[ 8, 9, 4 ],
15+
[ 7, 6, 5 ]
16+
]
17+
18+
Solution: ...
19+
*/
20+
publicclassSolution {
21+
publicint[][]generateMatrix(intn) {
22+
if (n <=0)returnnewint[0][0];
23+
int[][]res =newint[n][n];
24+
intm =n,row =0,col = -1,num =0;
25+
while (true) {
26+
for (inti =0;i <m; ++i)res[row][++col] = ++num;
27+
if (--n ==0)break;
28+
for (inti =0;i <n; ++i)res[++row][col] = ++num;
29+
if (--m ==0)break;
30+
for (inti =0;i <m; ++i)res[row][--col] = ++num;
31+
if (--n ==0)break;
32+
for (inti =0;i <n; ++i)res[--row][col] = ++num;
33+
if (--m ==0)break;
34+
}
35+
returnres;
36+
}
37+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp