Spiral Matrix问题及解法
来源:互联网 发布:linux 用户管理 列表 编辑:程序博客网 时间:2024/06/05 16:40
问题描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
示例:
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]
.
对于这种回旋状:右---下---左---上(循环),我们可以设置一个标志数组,记录是否便利过该位置的值,进而求的答案。
过程详见代码:
class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res;int m = matrix.size();if (m == 0) return res;int n = matrix[0].size();int num = m * n;int dict = 0; // right - 0; down - 1; left - 2; up - 3int row = 0, col = 0;vector<vector<int>> used(m, vector<int>(n, 0));for (int i = 0; i < num;){switch (dict){case 0: if (col < n){if (!used[row][col]){used[row][col] = 1;res.push_back(matrix[row][col]);col++; i++;}else{dict = (dict + 1) % 4;row++;col--;}}else{col--;dict = (dict + 1) % 4;row++;}break;case 1:if (row < m){if (!used[row][col]){used[row][col] = 1;res.push_back(matrix[row][col]);row++; i++;}else{dict = (dict + 1) % 4;col--;row--;}}else{row--;dict = (dict + 1) % 4;col--;}break;case 2:if (col >= 0){if (!used[row][col]){used[row][col] = 1;res.push_back(matrix[row][col]);col--; i++;}else{dict = (dict + 1) % 4;col++;row--;}}else{col++;row--;dict = (dict + 1) % 4;}break;case 3:if (row >= 0){if (!used[row][col]){used[row][col] = 1;res.push_back(matrix[row][col]);row--; i++;}else{dict = (dict + 1) % 4;row++;col++;}}else{dict = (dict + 1) % 4;row++;col++;}break;}}return res; }};
阅读全文
0 0
- Spiral Matrix问题及解法
- Spiral Matrix II问题及解法
- Reshape the Matrix问题及解法
- Set Matrix Zeroes问题及解法
- leetcode Spiral Matrix 的c++解法
- Leetcode之 Spiral Matrix 问题
- Search a 2D Matrix问题及解法
- Kth Smallest Element in a Sorted Matrix问题及解法
- Search a 2D Matrix II问题及解法
- Leetcode之Spiral Matrix II 问题
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- 软件安装
- FZU 2275 Game (KMP)
- django实现用户登陆功能
- (贪心)Codeforces Round #402 B. Weird Rounding
- 1.回看JAVA之变量类型
- Spiral Matrix问题及解法
- HDU6045-Is Derek lying?
- 论文阅读:Tooth and Alveolar Bone Segmentation from Dental Computed Tomography Images
- python中thread线程运用
- B
- JDBC连接数据库
- VMware完整克隆虚拟机后连不上网
- MFC入门之一:Icon与Menu
- Char和String的区别