leetcode 498. Diagonal Traverse 矩阵对角遍历 + 控制方向即可
2017-12-14 09:44
645 查看
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
本题题意很简单,就是对矩阵做一个对角遍历,其实可以遍历所有的对角,然后依次插入即可
代码如下:
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
本题题意很简单,就是对矩阵做一个对角遍历,其实可以遍历所有的对角,然后依次插入即可
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <cmath> using namespace std; class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& mat) { vector<int> res; if (mat.size() <= 0) return res; int row = mat.size(), col = mat[0].size(); for (int i = 0; i < row + col - 1; i++) { int x, y; if (i <= row - 1) { x = i; y = 0; } else { x = row - 1; y = i - row + 1; } vector<int> one; while (x >= 0 && y < col) one.push_back(mat[x--][y++]); if (i % 2 == 0) { for (int j = 0; j<one.size(); j++) res.push_back(one[j]); } else { for (int j = one.size() - 1; j >= 0; j--) res.push_back(one[j]); } } return res; } };
相关文章推荐
- 顺时针打印矩阵(方向控制)
- LeetCode—*Spiral Matrix问题,主要是用到了方向矩阵,很创意
- leetcode 329. Longest Increasing Path in a Matrix 矩阵中寻找最长递增序列 + 一个典型的深度优先遍历DFS的做法
- [LeetCode] Diagonal Traverse 对角线遍历
- [leetcode]498. Diagonal Traverse
- [leetcode] 498. Diagonal Traverse -- JavaScript 代码
- leetcode_498. Diagonal Traverse ? 待解决
- leetcode 130. Surrounded Regions 典型的深度优先遍历DFS + 矩阵遍历
- [LeetCode]498. Diagonal Traverse
- leetcode 598. Range Addition II 范围内的操作 + 遍历即可
- Leetcode 498. Diagonal Traverse
- LeetCode笔记:498. Diagonal Traverse
- leetcode 699. Falling Squares 俄罗斯方块的最高高度 + 暴力遍历即可
- LeetCode "498. Diagonal Traverse"
- leetcode 498. Diagonal Traverse
- LeetCode - 498. Diagonal Traverse
- leetcode 717. 1-bit and 2-bit Characters 编码判断问题 + 贪心算法 + 遍历即可
- 算法:按顺时针方向遍历矩阵
- LeetCode 498. Diagonal Traverse
- LeetCode: 498. Diagonal Traverse