Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1791944
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: C/C++

2013-05-25 11:13:15

最近帮同学写一个二维数组的回形遍历,看了一下,没什么好思路,百度,google了一把,使用递归算法还是比较好理解的,记录已备用
1 什么是螺旋遍历?
2 实现的思路是递归: 
Solution: There are several ways to solve this problem, but I am mentioning a method that is intuitive to understand and easy to implement. The idea is to consider the matrix similar to onion which can be peeled layer after layer. We can use the same approach to print the outer layer of the matrix and keep doing it recursively on a smaller matrix (with 1 less row and 1 less column).
图形理解:
3 C语言实现: 

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void print_layer_top_right(int a[][4], int col, int row, int collen, int rowlen);
  4. void print_layer_bottom_left(int a[][4], int col, int row, int collen, int rowlen);

  5. int main(void)
  6. {
  7. int a[5][4] = {
  8. {1,2,3,4},
  9. {5,6,7,8},
  10. {9,10,11,12},
  11. {13,14,15,16},
  12. {17,18,19,20}
  13. };

  14. print_layer_top_right(a,0,0,3,4);
  15. exit(0);
  16. }

  17. //
  18. // prints the top and right shells of the matrix
  19. //
  20. void print_layer_top_right(int a[][4], int col, int row, int collen, int rowlen)
  21. {
  22. int i = 0, j = 0;

  23. // print the row
  24. for(i = col; i<=collen; i++)
  25. {
  26. printf("%d,", a[row][i]);
  27. }

  28. //print the column
  29. for(j = row + 1; j <= rowlen; j++)
  30. {
  31. printf("%d,", a[j][collen]);
  32. }

  33. // see if we have more cells left
  34. if(collen-col > 0)
  35. {
  36. // 'recursively' call the function to print the bottom-left layer
  37. print_layer_bottom_left(a, col, row + 1, collen-1, rowlen);
  38. }
  39. }

  40. //
  41. // prints the bottom and left shells of the matrix

  42. void print_layer_bottom_left(int a[][4], int col, int row, int collen, int rowlen)
  43. {
  44. int i = 0, j = 0;

  45. //print the row of the matrix in reverse
  46. for(i = collen; i>=col; i--)
  47. {
  48. printf("%d,", a[rowlen][i]);
  49. }

  50. // print the last column of the matrix in reverse
  51. for(j = rowlen - 1; j >= row; j--)
  52. {
  53. printf("%d,", a[j][col]);
  54. }

  55. if(collen-col > 0)
  56. {
  57. // 'recursively' call the function to print the top-right layer
  58. print_layer_top_right(a, col+1, row, collen, rowlen-1);
  59. }
  60. }
4 ref: 
http://shashank7s.blogspot.com/2011/04/wap-to-print-2d-array-matrix-in-spiral.html


阅读(7622) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~