Skip to content

Instantly share code, notes, and snippets.

@Cee
Created May 16, 2014 03:34
Show Gist options
  • Save Cee/696cd4a4d4eadd224564 to your computer and use it in GitHub Desktop.
Save Cee/696cd4a4d4eadd224564 to your computer and use it in GitHub Desktop.
public class Solution {
public int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int i = 0;
int j = 0;
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
ret[i][j] = 0;
}
}
i = 0;
j = 0;
int count = 0;
int way = 1; // 1 right 2 down 3 left 4 right
while (count < n * n){
count++;
ret[i][j] = count;
if (way == 1){
if ((j + 1 < n) && (ret[i][j + 1] == 0)){
j++;
} else {
way = 2;
i++;
}
}else if (way == 2){
if ((i + 1 < n) && (ret[i + 1][j] == 0)){
i++;
} else {
way = 3;
j--;
}
}else if (way == 3){
if ((j - 1 >= 0) && (ret[i][j - 1] == 0)){
j--;
} else {
way = 4;
i--;
}
}else if (way == 4){
if ((i - 1 >= 0) && (ret[i - 1][j] == 0)){
i--;
} else {
way = 1;
j++;
}
}
}
return ret;
}
}
@Cee
Copy link
Author

Cee commented May 16, 2014

我去
其实可以用switch or %取模
结果if用了忘了用elseif导致每次都是往上走就overflow了简直233333

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment