Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

 

思路: 用标记法来实现循环控制,缺点会占用m*n的boolean空间,优点,简单,容易理解

用if控制循环方向,while来控制遍历该方向所有值

代码:

  1. public List<Integer> spiralOrder(int[][] matrix) {
  2. List<Integer> res = new ArrayList<Integer>();
  3. int h = matrix.length;
  4. if(h==0) return res;
  5. int w = matrix[0].length;
  6. if(w==0) return res;
  7. boolean[][] flag = new boolean[h][w];
  8. res.add(matrix[0][0]);
  9. flag[0][0] = true;
  10. int i=0;
  11. int j=0;
  12. while(true) {
  13. if(j+1<w && flag[i][j+1] == false) {
  14. while(j+1<w && flag[i][j+1] == false) {  //要在该方向查询完毕,否则可能有两个方向满足条件
  15. flag[i][j+1] = true;
  16. res.add(matrix[i][j+1]);
  17. j=j+1;
  18. }
  19. } else if(i+1<h && flag[i+1][j] == false) {
  20. while(i+1<h && flag[i+1][j] == false) {
  21. flag[i+1][j] = true;
  22. res.add(matrix[i+1][j]);
  23. i=i+1;
  24. }
  25. } else if(j-1>=0 && flag[i][j-1] == false) {
  26. while(j-1>=0 && flag[i][j-1] == false) {
  27. flag[i][j-1] = true;
  28. res.add(matrix[i][j-1]);
  29. j=j-1;
  30. }
  31. } else if(i-1>=0 && flag[i-1][j] == false) {
  32. while(i-1>=0 && flag[i-1][j] == false) {
  33. flag[i-1][j] = true;
  34. res.add(matrix[i-1][j]);
  35. i = i-1;
  36. }
  37. } else {
  38. break;
  39. }
  40. }
  41. return res;
  42. }

思路二: 用highrow、lowrow、lowcol、highcol四个变量控制遍历

C++代码:

  1. vector<int> spiralOrder(vector<vector<int> > &matrix) {
  2. int lowrow = 0;
  3. int lowcol = 0;
  4. vector<int> res;
  5. int highrow=matrix.size();
  6. if(highrow==0) return res;
  7. int highcol=matrix[0].size();
  8. highrow--;
  9. highcol--;
  10. int j=0;
  11. if(highrow==0) return matrix[0];
  12. while(true) {
  13. if(highrow<lowrow||highcol<lowcol) break;
  14. if(lowrow==highrow) {
  15. for(j=lowcol;j<=highcol;j++) {
  16. res.push_back(matrix[lowrow][j]);
  17. }
  18. break;
  19. }
  20. if(lowcol==highcol) {
  21. for(j=lowrow;j<=highrow;j++) {
  22. res.push_back(matrix[j][highcol]);
  23. }
  24. break;
  25. }
  26. for(j=lowcol;j<=highcol;j++) {
  27. res.push_back(matrix[lowrow][j]);
  28. }
  29. for(j=lowrow+1;j<=highrow;j++) {
  30. res.push_back(matrix[j][highcol]);
  31. }
  32. for(j=highcol-1;j>=lowcol;j--) {
  33. res.push_back(matrix[highrow][j]);
  34. }
  35. for(j=highrow-1;j>lowrow;j--) {
  36. res.push_back(matrix[j][lowcol]);
  37. }
  38. lowrow++;
  39. lowcol++;
  40. highcol--;
  41. highrow--;
  42. }
  43. return res;
  44. }
posted @ 2014-07-26 11:23  purejade  阅读(109)  评论(0)    收藏  举报