Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]


思路: 控制好边界条件

  1. public int[][] generateMatrix(int n) {
  2. int[][] res = new int[n][n];
  3. int num = 1;
  4. // int n2 = Math.pow(n,2);
  5. int highrow = n-1;
  6. int highcol = n-1;
  7. int lowrow = 0;
  8. int lowcol = 0;
  9. while(true) {
  10. if(lowrow>highrow || lowcol > highcol) {
  11. break;
  12. }
  13. if(highrow==lowrow) {
  14. for(int i=lowcol;i<=highcol;i++) {
  15. res[lowrow][i] = num++;
  16. }
  17. break;
  18. }
  19. if(highcol == lowcol) {
  20. for(int i=lowrow;i<=highrow;i++) {
  21. res[i][lowcol] = num++;
  22. }
  23. break;
  24. }
  25. for(int i=lowcol;i<=highcol;i++) {
  26. res[lowrow][i] = num++;
  27. }
  28. for(int i=lowrow+1;i<=highrow;i++) {
  29. res[i][highcol] = num++;
  30. }
  31. for(int i=highcol-1;i>=lowcol;i--) {
  32. res[highrow][i] = num++;
  33. }
  34. for(int i=highrow-1;i>=lowrow+1;i--) {  //注意最后一个边界
  35. res[i][lowcol] = num++;
  36. }
  37. highrow--;
  38. highcol--;
  39. lowrow++;
  40. lowcol++;
  41. }
  42. return res;
  43. }
posted @ 2014-07-26 11:44  purejade  阅读(74)  评论(0)    收藏  举报