[leetcode-54-Spiral Matrix]
生活随笔
收集整理的這篇文章主要介紹了
[leetcode-54-Spiral Matrix]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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].
思路:
上下左右4個變量分別表示邊界,如果越界,結束循環。
vector<int> spiralOrder(vector<vector<int>>& matrix){if (matrix.empty())return{};int m = matrix.size(), n = matrix[0].size();vector<int> spiral(m*n);int up = 0, down = m - 1, left = 0, right = n - 1, k = 0;while (1){for (int col = left; col <= right; col++)spiral[k++] = matrix[up][col];if (++up > down)break;for (int row = up; row <= down; row++)spiral[k++] = matrix[row][right];if (--right < left)break;for (int col = right; col >= left; col--)spiral[k++] = matrix[down][col];if (--down < up)break;for (int row = down; row >= up; row--)spiral[k++] = matrix[row][left];if (++left > right)break; }return spiral;}參考:
https://discuss.leetcode.com/topic/21090/0ms-clear-c-solution
轉載于:https://www.cnblogs.com/hellowooorld/p/6930538.html
總結
以上是生活随笔為你收集整理的[leetcode-54-Spiral Matrix]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: microsoftedge浏览器如何设置
- 下一篇: Linux 下禅道和 SVN、GIT 集