Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or
2015-11-26 20:23
513 查看
1. Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<vector<int>> m = { { 1, 2,3 }, { 2, 3 ,4}, { 4, 5 ,5} };
cout << m.size() << " " << m[0].size() << endl;
//进行螺旋输出
int x1 = 0, y1 = 0;
int x2 = m.size() - 1;
int y2 = m[0].size() - 1;
vector<int>r;
while (x1 <= x2 && y1 <= y2)
{
//对上面的一层进行处理
for (int y = y1; y <= y2; y++)
r.push_back(m[x1][y]);
//对右边进行处理
for (int x = x1 + 1; x <= x2; x++)
r.push_back(m[x][y2]);
//对下面的进行处理
for (int y = y2 - 1; y > y1; --y)
r.push_back(m[x2][y]);
for (int x = x2 - 1; x > x1; x--)
r.push_back(m[x][y1]);
x1++; y1++; x2--; y2--;
}
for (size_t i = 0; i < r.size(); i++)
cout << r[i] << endl;
system("pause");
return 0;
}
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<vector<int>> m = { { 1, 2,3 }, { 2, 3 ,4}, { 4, 5 ,5} };
cout << m.size() << " " << m[0].size() << endl;
//进行螺旋输出
int x1 = 0, y1 = 0;
int x2 = m.size() - 1;
int y2 = m[0].size() - 1;
vector<int>r;
while (x1 <= x2 && y1 <= y2)
{
//对上面的一层进行处理
for (int y = y1; y <= y2; y++)
r.push_back(m[x1][y]);
//对右边进行处理
for (int x = x1 + 1; x <= x2; x++)
r.push_back(m[x][y2]);
//对下面的进行处理
for (int y = y2 - 1; y > y1; --y)
r.push_back(m[x2][y]);
for (int x = x2 - 1; x > x1; x--)
r.push_back(m[x][y1]);
x1++; y1++; x2--; y2--;
}
for (size_t i = 0; i < r.size(); i++)
cout << r[i] << endl;
system("pause");
return 0;
}
相关文章推荐
- java的poi技术读取Excel
- 利用FRDM-K20D50M开发板制作USBDM/Pemicro_OpenSDA仿真调试器
- ROS代码经验系列-- tf进行位置查询变换
- ubantu server 服务器版配置mantis
- 阿里云nat mysql配置
- HTML 5 canvas globalCompositeOperation 属性
- Qt5 程序启动画面动图效果
- Project Euler 84:Monopoly odds 大富翁几率
- Machine Learning week 8 quiz: Principal Component Analysis
- ubuntu15.10install-mac-theme - Linux系统教程
- 关于sql语句的一点总结
- c++11 async启动异步任务的使用方法
- easyui(from)表单json格式转换
- 学习日记--PinnedSectionListView(类似通讯录分组)的测试
- 树状数组模板
- I,P,B帧和PTS,DTS的关系
- debain的useradd默认没有主目录及shell
- iOS开发——来改掉那些已经过时的方法吧(持续更新中)
- 中文句法分析
- 中文句法分析