题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。例如:
输入一个矩阵如下:
1 1 2 3 4 2 5 6 7 8 3 9 10 11 12 4 13 14 15 16
则依次打印出数字:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
这道题的类似于:http://www.cnblogs.com/vpoet/p/4660520.html(LeeCode-Spiral Matrix 11)
其实主要还是考察我们对二维数组的循环操作:
代码实现如下:
1 #include <iostream> 2 using namespace std; 3 4 void PrintMatrixClockwisely(int** numbers,int columns,int rows) 5 { 6 cout<<endl<<"The Matrix is: "<<endl;; 7 for(int i=0;i<rows;i++) 8 { 9 for(int j=0;j<columns;j++) 10 { 11 cout<<numbers[i][j]<<" "; 12 } 13 cout<<endl; 14 } 15 16 cout<<endl<<"The Output Array of Matrix is: "; 17 18 19 int count=0; 20 int left=0; 21 int top=0; 22 int bottom=rows-1; 23 int right=columns-1; 24 while(count<(columns*rows)) 25 { 26 for(i=left;i<=right;i++) 27 { 28 cout<<numbers[left][i]<<" "; 29 count++; 30 } 31 top++; 32 33 34 for(i=top;i<=bottom;i++) 35 { 36 cout<<numbers[i][right]<<" "; 37 count++; 38 } 39 right--; 40 41 for(i=right;i>=left;i--) 42 { 43 cout<<numbers[bottom][i]<<" "; 44 count++; 45 } 46 bottom--; 47 48 for(i=bottom;i>=top;i--) 49 { 50 cout<<numbers[i][left]<<" "; 51 count++; 52 } 53 left++; 54 55 } 56 } 57 58 59 60 void main() 61 { 62 int **nums; 63 int cols; 64 int rows; 65 int i,j; 66 cout<<"Please input the rows: "; 67 cin>>rows; 68 69 cout<<"Please input the cols: "; 70 cin>>cols; 71 72 nums=new int*[rows]; 73 for(i=0;i<rows;i++) 74 nums[i]=new int[cols]; 75 76 77 for(i=0;i<rows;i++) 78 { 79 cout<<"Please input the "<<i+1<<"th"<<" rows: "<<endl;; 80 for(j=0;j<cols;j++) 81 { 82 int data; 83 cin>>data; 84 nums[i][j]=data; 85 } 86 } 87 88 89 PrintMatrixClockwisely(nums,cols,rows); 90 91 92 for(i=0;i<rows;i++) 93 delete[] nums[i]; 94 delete[] nums; 95 return; 96 }
运行截图: