给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素。
例如,给出以下矩阵:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
应该返回 [1,2,3,6,9,8,7,4,5]。
详见:https://leetcode.com/problems/spiral-matrix/description/

Java实现:

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<Integer>();
if(matrix==null||matrix.length==0){
return res;
}
int row=matrix.length;
int col=matrix[0].length; int top=0;
int bottom=row-1;
int left=0;
int right=col-1;
while(top<=bottom&&left<=right){
for(int j=left;j<=right;++j){
res.add(matrix[top][j]);
}
++top;
for(int i=top;i<=bottom;++i){
res.add(matrix[i][right]);
}
--right;
if(top<=bottom){
for(int j=right;j>=left;--j){
res.add(matrix[bottom][j]);
}
}
--bottom;
if(left<=right){
for(int i=bottom;i>=top;--i){
res.add(matrix[i][left]);
}
}
++left;
}
return res;
}
}

C++实现:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty())
return res; int row = matrix.size();
int col = matrix[0].size(); int top = 0;
int bottom = row - 1;
int left = 0;
int right = col - 1; //螺旋曲线,运动轨迹总是一致的
while (top <= bottom && left <= right)
{
//向右列递增遍历
for (int j = left; j <= right; j++)
{
res.push_back(matrix[top][j]);
}
top++; //遍历后,去掉此行 //向下行递增遍历
for (int i = top; i <= bottom; i++)
{
res.push_back(matrix[i][right]);
}
right--; //遍历后,去掉此列 if (top <= bottom) //重要判断,防止重复
{
//向左列递减遍历
for (int j = right; j >= left; j--)
{
res.push_back(matrix[bottom][j]);
} }
bottom--; //遍历后,去掉此行 if (left <= right) //重要判断,防止重复
{
//向上行递减遍历
for (int i = bottom; i >= top; i--)
{
res.push_back(matrix[i][left]);
}
}
left++; //遍历后,去掉此列
} return res;
}
};

最新文章

  1. Spring学习记录(十一)---使用注解和自动装配
  2. PHP访问带密码的Redis
  3. PHP执行定时任务
  4. centos 下 django 1.8 配置好后 admin 后台无法显示 样式解决办法
  5. PHP中正则替换函数preg_replace用法笔记
  6. JS框架整理
  7. Python 基础篇:字典、集合、文件操作
  8. destoon实现调用热门关键字的方法
  9. POJ 2479-Maximum sum(线性dp)
  10. POJ 2050 Searching the Web
  11. SharePoint2013 Excel导出好的代码
  12. WIMP环境搭建
  13. 工作中MySql的了解到的小技巧
  14. 生鲜配送管理系统_升鲜宝供应链系统V2.0 设计思想及主要模块,欢迎大家批评指点。
  15. C# 显示纯文本对齐封装(控制显示字体长度)
  16. hdu3790 dijkstra+堆优化
  17. AD7729_双通道Sigma-Delta ADC
  18. 拦截$.ajax方法实现登录过期登录
  19. hdu6444 Neko&#39;s Loop
  20. Snmp学习总结(三)——Win7安装和配置SNMP

热门文章

  1. UML中的6大关系详细说明
  2. overflow:hidden真的失效了吗?
  3. PG替换字段中的回车与换行
  4. 「JLOI2011」「LuoguP4568」飞行路线(分层图最短路
  5. python定时任务:apscheduler的使用(还有一个celery~)
  6. bzoj 4671 异或图 —— 容斥+斯特林反演+线性基
  7. POJ3660(foyld闭包问题)
  8. exosip 和 pjsip 简介
  9. 关于java基础中,接口里面父类的对象指向子类的引用
  10. ZOJ 2671 Cryptography 矩阵乘法+线段树