二维数组回形遍历

来源:互联网 发布:淘宝客服的回复技巧 编辑:程序博客网 时间:2024/05/06 01:31

如图所示,打印遍历后的结果。

策略:由外到内,一圈圈的打印,直到没有元素输出。

#include <iostream>using namespace std;int print_array_round(int **a, int row_start,int row_end, int col_start, int col_end) {  int count = 0; //本次打印的元素个数  // 右  for(int i=col_start;i<=col_end;++i) {    cout<<a[row_start][i]<<" ";    ++count;  }  // 下  for(int i = row_start+1; i<=row_end;++i) {    cout<<a[i][col_end]<<" ";    ++count;  }  // 左  for(int i=col_end-1;i>=col_start;--i) {    cout<<a[row_end][i]<<" ";    ++count;  }  // 上  for (int i=row_end-1;i>=row_start+1;--i) {    cout<<a[i][col_start]<<" ";    ++count;  }  return count;}void print_array(int **a, int row,int col) {  int row_start = 0;  int row_end = row-1;  int col_start = 0;  int col_end = col-1;  int count = print_array_round(a,row_start,row_end,col_start,col_end);  while (count) {    ++row_start;    --row_end;    ++col_start;    --col_end;    count = print_array_round(a,row_start,row_end,col_start,col_end);  }}int _tmain(int argc, _TCHAR* argv[]){  int a[][3] = {1,2,3,4,5,6,7,8,9,10,11,12};    int **p = new int*[4];    for (int i=0;i<4;i++) {    p[i] = new int[3];    for (int j=0;j<3;j++) {      p[i][j] = a[i][j];    }  }  print_array(p,4,3);  system("pause");  return 0;}