【面试题】剑指offer20
来源:互联网 发布:图像自动拼接软件 编辑:程序博客网 时间:2024/04/30 18:25
题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
输出
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
代码
#include<iostream>#include<cstdlib>using namespace std;void PrintMatrixInCricle(int arr[],int cols,int rows,int start){ int endX=cols-1-start; int endY=rows-1-start; for(int i=start;i<=endX;i++)//从左到右打印一行 { int num=arr[start*rows+i]; cout<<num<<" "; } if (start<endY)//从上到下打印一列 { for(int i=start+1;i<=endY;i++) { int num=arr[i*rows+endX]; cout<<num<<" "; } } if(start<endX&&start<endY) { for(int i=endX-1;i>=start;i--) { int num=arr[endY*rows+i]; cout<<num<<" "; } } if(start<endX&&start<endY-1) { for(int i=endY-1;i>=start+1;i--) { int num=arr[i*rows+start]; cout<<num<<" "; } } cout<<endl;}void PrintMatrix(int arr[],int cols,int rows){ if (arr==NULL||cols<=0||rows<=0) return; int start=0; while (cols>start*2&&rows>start*2) { PrintMatrixInCricle(arr,cols,rows,start); ++start; }}void test(){ int arr[]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; PrintMatrix(arr,4,4);}
#include "Matrix.h"int main(){ test(); system("pause"); return 0;}
结果
0 0
- 【面试题】剑指offer20
- 【面试题】剑指offer20--顺时针打印一个矩阵的数字
- 剑指offer20:顺时针打印矩阵
- 剑指Offer20:顺时针打印矩阵
- 剑指offer20顺时针打印矩阵
- 剑指offer20--栈的压入,弹出序列
- 剑指offer 面试题
- 【面试题】剑指offer10
- 【面试题】剑指offer11
- 剑指offer面试题
- 【面试题】剑指offer14
- 【面试题】剑指offer18
- 【面试题】剑指offer21
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- 剑指offer面试题08
- python 笔记4
- Java反射机制详解(转载)
- 各邮箱smtp服务器及支持的协议
- 组内菜鸟学习班
- [CRT][中国剩余定理]CRT小结
- 【面试题】剑指offer20
- 翻译:如何使用CSS实现多行文本的省略号显示
- python中list,tuple,dict,set的区别及联系
- OpenGL顶点数组对象(vertex Array Object)VAO
- Spring学习文档
- spring基础环境搭建
- Linux Kernel设备驱动模型之 Power 管理
- 最大子字符串,哈希,O(n)
- 监听Symfony日志 将500错误发送到微信