博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Spiral Matrix
阅读量:7188 次
发布时间:2019-06-29

本文共 1224 字,大约阅读时间需要 4 分钟。

The idea is just to add the elements in the spiral order. First the up-most row (u), then the right-most column (r), then the down-most row (d), and finally the left-most column (l). After finishing a row or a column, update the corresponding variable to continue the process.

The code is as follows.

1 class Solution { 2 public: 3     vector
spiralOrder(vector
>& matrix) { 4 if (matrix.empty()) return {}; 5 int m = matrix.size(), n = matrix[0].size(); 6 vector
spiral(m * n); 7 int u = 0, d = m - 1, l = 0, r = n - 1, k = 0; 8 while (true) { 9 // up10 for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];11 if (++u > d) break;12 // right13 for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];14 if (--r < l) break;15 // down16 for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];17 if (--d < u) break;18 // left19 for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];20 if (++l > r) break;21 }22 return spiral;23 }24 };

 

转载地址:http://jzfkm.baihongyu.com/

你可能感兴趣的文章
使用apache daemon让java程序在unix系统上以服务方式运行
查看>>
WampServer 3.1.0 所需VC运行库下载及安装说明
查看>>
ThinkPHP 模板魔术常量
查看>>
添加非浮动的清楚元素围住浮动元素
查看>>
CentOS挂载NTFS盘符问题
查看>>
文档里组件中的methods方法调用
查看>>
Play 2.0 用户指南 - 异步HTTP编程 --针对Scala开发者
查看>>
Swift 2.0 异常处理
查看>>
Java学习之Xml系列二:xml按条件查询、xml递归遍历所有元素和属性
查看>>
Tomcat7 redis session共享
查看>>
用逻辑运算符实现三目运算符
查看>>
php的openssl_private_encrypt的python实现
查看>>
JDK8新特性(3):Stream API补充介绍
查看>>
php连接状态测试(运行中 关闭浏览器)
查看>>
整合springMVC,Mybatis的Maven项目框架
查看>>
Keras 线性回归
查看>>
Oracle优化查询改写(第二章-给查询结果排序)
查看>>
PHP实现排列组合
查看>>
Fragment的commit的注意事项
查看>>
[UE4]LOG
查看>>