59 Spiral Matrix II
Given an integern, generate a square matrix filled with elements from 1 ton2in spiral order.
For example,
Givenn=3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution)
class Solution {
public int[][] generateMatrix(int n) {
if (n == 0) return new int[0][0];
int[][] result = new int[n][n];
int count = 1;
int step = 0;
while(count < n*n) {
int i = step;
int j = step;
for (; j < n-step-1; j++) result[i][j] = count++;
for (; i < n-step-1; i++) result[i][j] = count++;
for (; j > step; j--) result[i][j] = count++;
for (; i > step; i--) result[i][j] = count++;
step++;
}
if (result[step][step] == 0)
result[step][step] = count;
return result;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int left = -1,top = 0;
int right = n -1,down = n - 1;
int count = 1;
while (left <= right) {
for (int j = ++left; j <= right; j++) ret[top][j] = count++;
for (int i = ++top; i <= down; i++) ret[i][right] = count++;
for (int j = --right; j >= left; j--) ret[down][j] = count++;
for (int i = --down; i >= top; i--) ret[i][left] = count++;
}
return ret;
}
}
class Solution {
public int[][] generateMatrix(int n) {
if (n==0) return new int[n][n];
int[] dc = new int[]{1,0,-1,0};
int[] dr = new int[]{0,1,0,-1};
int dir = 0, val=0, r=0, c=0,limit=n*n;
int[][] matrix = new int[n][n];
while (val++ < limit) {
matrix[r][c] = val;
r += dr[dir];
c += dc[dir];
if (isInvalid(matrix,r, c)) {
r-= dr[dir];
c-=dc[dir];
dir = (dir+1)%4;
r+= dr[dir];
c+= dc[dir];
}
}
return matrix;
}
private static boolean isInvalid(int[][] m, int r, int c) {
return r<0||c<0||r>=m.length||c>= m.length||m[r][c] != 0;
}
}