题目:

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]. (Medium)

分析:

题目没有什么复杂的算法要应用,就是一行一列输出,处理好细节即可。

比较清晰的写法是搞一个rowBegin, rowEnd, colBegin, colEnd, 并在处理完一行/一列后更新值,并判断是否仍然满足 rowBegin <= rowEnd && colBegin <= colEnd

代码:

 class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.size() == ) {
return result;
}
int m = matrix.size(), n = matrix[].size();
int rowBegin = , rowEnd = m - , colBegin = , colEnd = n - ;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; ++i ) {
result.push_back(matrix[rowBegin][i]);
}
rowBegin++;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowBegin; i <= rowEnd; ++i) {
result.push_back(matrix[i][colEnd]);
}
colEnd--;
if (colBegin > colEnd) {
break;
}
for (int i = colEnd; i >= colBegin; --i) {
result.push_back(matrix[rowEnd][i]);
}
rowEnd--;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowEnd; i>= rowBegin; --i) {
result.push_back(matrix[i][colBegin]);
}
colBegin++;
}
return result;
}
};

最新文章

  1. java web学习总结(十二) -------------------Session
  2. php curl用法
  3. ionic不同view跳转到同一个
  4. BZOJ3898 : 打的士
  5. cocos2dx 3.x(屏幕截图的两种方法)
  6. 关于iPhone多点触控
  7. Http抓包工具Charlse使用教程
  8. Swift中的延迟加载(懒加载)
  9. Ubuntu apache 禁止目录浏览
  10. socket编程——一个简单的例子
  11. hibernate---一对一单向主键关联(不重要)
  12. Android自定义控件之TextView
  13. 【转】IO流程
  14. three.js 相机
  15. javascript获取网页地址栏的id
  16. 03 Button 按钮
  17. 服务器端配置nodejs环境(使用pm2进程管理运行)
  18. Linux系统KVM虚拟化技术
  19. HotSpot虚拟机
  20. python3编译安装no module named _ssl

热门文章

  1. DynamicDataDisplay 双击获取坐标
  2. JavaScript如何实现字符串拼接操作
  3. [jnhs]hibernate只能创建一张/表不创建表com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table &#39;kaihu.t_client_info&#39; doesn&#39;t exist和org.hibernate.exception.SQLGrammarException: could not execute statement
  4. TomCat 启动默认加载项目
  5. Ubuntu18.04 修改IP地址、查看网关、防火墙
  6. 验证码倒计时js
  7. RSA 2019安全大会:企业资产管理成行业新风向标,云上安全占优势
  8. 阿里云杨敬宇:5G时代,边缘计算将发挥更大价值
  9. 【python之路15】深浅拷贝及函数
  10. 层次分析法MATLAB