LeetCode 54.Spiral Matrix (Medium)
2017-09-08 23:45
351 查看
原题地址:https://leetcode.com/problems/spiral-matrix/description/
题目描述:
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].
题解:
题意既是要求将矩阵按顺时针打印,解法比较简单, 每次循环按顺序分别打印四条边即可。
用变量作游标标识出当前打印的数字的位置,每次打印完一周后,游标指向新生成的矩阵的第一个元素所在的位置,开始新一轮的打印。当打印的元素数等于矩阵总元素数后,跳出循环,返回生成的vector< int > 变量。
打印时只需注意每次循环时行数和列数是在变化的,因此打印四条边时要注意给上下限加上或减去当前循环圈数(queryNum)
代码:
22 / 22 test cases passed.
Status: Accepted
Runtime: 3 ms
题目描述:
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].
题解:
题意既是要求将矩阵按顺时针打印,解法比较简单, 每次循环按顺序分别打印四条边即可。
用变量作游标标识出当前打印的数字的位置,每次打印完一周后,游标指向新生成的矩阵的第一个元素所在的位置,开始新一轮的打印。当打印的元素数等于矩阵总元素数后,跳出循环,返回生成的vector< int > 变量。
打印时只需注意每次循环时行数和列数是在变化的,因此打印四条边时要注意给上下限加上或减去当前循环圈数(queryNum)
代码:
class Solution { public: vector<int> spiralOrder(vector<vector<int> >& matrix) { if (matrix.size() == 0) return vector<int>(); //行数和列数 int row = matrix.size(), col = matrix[0].size(); int x = 0, y = 0; //x, y为游标横纵坐标 int cntNumber = col*row; //cntNumber为矩阵元素总数 int count = 0, queryNum = 0; //count当前打印元素数, queryNum当前循环数 vector<int> output(cntNumber); while (true) { for (; y < col - queryNum; y++) { output[count++] = matrix[x][y]; } y--; x++; if (count == cntNumber) break; for (; x < row - queryNum; x++) { output[count++] = matrix[x][y]; } x--; y--; if (count == cntNumber) break; for (; y >= queryNum; y--) { output[count++] = matrix[x][y]; } y++; x--; if (count == cntNumber) break; for (; x > queryNum; x--) { output[count++] = matrix[x][y]; } x++; y++; if (count == cntNumber) break; queryNum++; } return output; } };
22 / 22 test cases passed.
Status: Accepted
Runtime: 3 ms
相关文章推荐
- LeetCode-54-Spiral Matrix(矩阵/模拟/递归)-Medium
- 【LeetCode】(54)Spiral Matrix(Medium)
- [Leetcode 54, Medium] Spiral Matrix
- Leetcode 54. Spiral Matrix (Medium) (cpp)
- Leetcode 54. Spiral Matrix (Medium) (java)
- LeetCode 54 Spiral Matrix
- LeetCode 54 - Spiral Matrix
- leetcode 54 : Spiral Matrix
- [LeetCode]Spiral Matrix 54
- Leetcode 54 Spiral Matrix
- Leetcode 54, Spiral Matrix
- LeetCode------54. Spiral Matrix(螺旋二维矩阵)-----59. Spiral Matrix II(n的螺旋矩阵)
- LeetCode54——Spiral Matrix
- Leetcode 54 spiral matrix II (螺旋矩阵)
- leetCode 54.Spiral Matrix(螺旋矩阵) 解题思路和方法
- leetcode-54 Spiral Matrix 顺时针打印矩阵(《剑指offer》面试题20)
- LeetCode-59-Spiral Matrix II(Array)-Medium
- [leetcode-54]Spiral Matrix(C语言)
- leetcode-54. Spiral Matrix(打印蛇形矩阵)
- Leetcode 54 Spiral Matrix