剑指offer-面试题20.顺时针打印矩阵

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。例如:

输入一个矩阵如下:

 

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 }

 

运行截图:

 

转载于:https://www.cnblogs.com/vpoet/p/4674103.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值