public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if(n<1) return res;
int dir = 0;// 0 means direction is from left to right, 1 means from up to down, 2 right to up,
// 3 down to up
int length = n;
int val = 1, i = 0, j = 0;
while(val <= Math.pow(n,2)){
int steps = 0;
if(dir == 0){// i is fixed, j should increase
for(;steps < length && val <= Math.pow(n,2);steps++){ res[i][j+steps] = val; val++;}
dir = (++dir)%4;
length --;
i++;
j = j + steps - 1;
}else{
if(dir == 1){// j is fixed, i should increase
for(;steps < length && val <= Math.pow(n,2);steps++){ res[i+steps][j] = val; val++;}
dir = (++dir)%4;
j--;
i = i + steps - 1;
}
else{
if(dir == 2){// i is fixed, j should decrease
for(;steps < length && val <= Math.pow(n,2);steps ++){ res[i][j-steps] = val; val++;}
dir = (++dir)%4;
length --;
i --;
j = j - (steps - 1);
}
else{
if(dir == 3){// j is fixed, i should decrease
for(;steps < length && val <= Math.pow(n,2);steps ++){ res[i - steps][j] = val; val++;}
dir = (++dir)%4;
j ++;
i = i - (steps - 1);
}
}
}
}
}
return res;
}
}
UPDATE:
Recently I was preparing for one interview, and happened to work on this question again. Below is another implementation of my algorithm, which is much cleaner:
public class Solution {
public int[][] generateMatrix(int n) {
//if(n <= 0) return null;
int[][] res = new int[n][n];
int m = 1, i = 0, j = 0;
int end = n*n;//Math.pow(n,2);
while(m <= end){
for(j = i; (j <= n - 1 - i) && ( m <= end) ; j++){ res[i][j] = m ; m ++;} j--;
for(i++; i <= j && m <= end; i++){ res[i][j] = m ; m ++;} i--;
for(j--; (j >= n-1-i) && (m <= end); j--){ res[i][j] = m ; m ++;} j++;
for(i--; i >= j+1 && m <= end; i--){ res[i][j] = m ; m ++;} i++;
}
return res;
}
}
No comments:
Post a Comment