Created
May 16, 2014 03:34
-
-
Save Cee/696cd4a4d4eadd224564 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我去
其实可以用switch or %取模
结果if用了忘了用elseif导致每次都是往上走就overflow了简直233333