Spiral Matrix II
Source
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in
spiral order.
Example
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Java
public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int start=0;
int end=n-1;
int count=1;
while(start<end){
for(int i=start; i<end; i++){
result[start][i]=count;
count++;
}
for(int i=start; i<end; i++){
result[i][end]=count;
count++;
}
for(int i=end; i>start; i--){
result[end][i]=count;
count++;
}
for(int i=end; i>start; i--){
result[i][start]=count;
count++;
}
start++;
end--;
}
if(start==end){
result[start][end]=count;
}
return result;
}
}
Python
class Solution:
def generateMatrix(self, n):
result=[[0 for x in range(n)] for x in range(n)]
start=0
end=n-1;
count=1
while start<end:
for i in range(start, end):
result[start][i] = count
count+=1
for i in range(start, end):
result[i][end] = count
count+=1
for i in range(end, start, -1):
result[end][i] = count
count+=1
for i in range(end, start, -1):
result[i][start] = count
count+=1
start+=1
end-=1
if start==end:
result[start][end]=count
return result