LeetCode – Refresh – Spiral Matrix

本文介绍了一种螺旋遍历矩阵的算法实现,该算法能够按螺旋顺序遍历二维矩阵,并处理不同尺寸矩阵的情况,包括奇数和偶数边长的特殊情况。

When finally check the middle line, it is checking whether the min(n, m) is odd or even number.

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 4         vector<int> result;
 5         if (matrix.size() == 0) return result;
 6         int n = matrix.size(), m = matrix[0].size(), rec = min(n, m)/2;
 7         for (int i = 0; i < rec; i++) {
 8             for (int j = i; j < m-i-1; j++) result.push_back(matrix[i][j]);
 9             for (int j = i; j < n-i-1; j++) result.push_back(matrix[j][m-i-1]);
10             for (int j = m-i-1; j > i; j--) result.push_back(matrix[n-i-1][j]);
11             for (int j = n-i-1; j > i; j--) result.push_back(matrix[j][i]);
12         }
13         if (rec*2 != min(m, n)) {
14             if (n > m) {
15                 for (int i = rec; i <= n-rec-1; i++) result.push_back(matrix[i][m/2]);
16             } else {
17                 for (int i = rec; i <= m-rec-1; i++) result.push_back(matrix[n/2][i]);
18             }
19         }
20         return result;
21     }
22 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4362722.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值