Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:Given n =
3
,[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. | |
For example, | |
Given n = 3, | |
You should return the following matrix: | |
[ | |
[ 1, 2, 3 ], | |
[ 8, 9, 4 ], | |
[ 7, 6, 5 ] | |
] | |
""" | |
class Solution: | |
# @return a list of lists of integer | |
def generateMatrix(self, n): | |
if n<=0: | |
return [] | |
# row[:] mean shallow copy each row in [[0]*n]*n | |
# we cannot not use row replace row[:] here | |
matrix=[row[:] for row in [[0]*n]*n] | |
row_st=0 | |
row_ed=n-1 | |
col_st=0 | |
col_ed=n-1 | |
current=1 | |
while (True): | |
if current>n*n: | |
break | |
for c in range (col_st, col_ed+1): | |
matrix[row_st][c]=current | |
current+=1 | |
row_st+=1 | |
for r in range (row_st, row_ed+1): | |
matrix[r][col_ed]=current | |
current+=1 | |
col_ed-=1 | |
for c in range (col_ed, col_st-1, -1): | |
matrix[row_ed][c]=current | |
current+=1 | |
row_ed-=1 | |
for r in range (row_ed, row_st-1, -1): | |
matrix[r][col_st]=current | |
current+=1 | |
col_st+=1 | |
return matrix |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. | |
For example, | |
Given n = 3, | |
You should return the following matrix: | |
[ | |
[ 1, 2, 3 ], | |
[ 8, 9, 4 ], | |
[ 7, 6, 5 ] | |
] | |
public class Solution { | |
public int[][] generateMatrix(int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if (n<=0){ | |
return new int[0][0]; | |
} | |
int [][] matrix=new int[n][n]; | |
int beginX=0; | |
int endX=n-1; | |
int beginY=0; | |
int endY=n-1; | |
int current=1; | |
while (current<=n*n){ | |
for (int col=beginX; col<=endX; col++){ | |
matrix[beginY][col]=current++; | |
} | |
beginY++; | |
for (int row=beginY; row<=endY; row++){ | |
matrix[row][endX]=current++; | |
} | |
endX--; | |
for (int col=endX; col>=beginX; col--){ | |
matrix[endY][col]=current++; | |
} | |
endY--; | |
for (int row=endY; row>=beginY; row--){ | |
matrix[row][beginX]=current++; | |
} | |
beginX++; | |
} | |
return matrix; | |
} | |
} |
No comments:
Post a Comment