LeetCode59 Spiral Matrix II
2016-09-19 22:16
459 查看
题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix: (Medium)
分析:
跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。
代码:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
3,
You should return the following matrix: (Medium)
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
分析:
跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。
代码:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> result(n, vector<int>(n,0)); int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1; int count = 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; ++i ) { result[rowBegin][i] = count; count++; } rowBegin++; if (rowBegin > rowEnd) { break; } for (int i = rowBegin; i <= rowEnd; ++i) { result[i][colEnd] = count; count++; } colEnd--; if (colBegin > colEnd) { break; } for (int i = colEnd; i >= colBegin; --i) { result[rowEnd][i] = count; count++; } rowEnd--; if (rowBegin > rowEnd) { break; } for (int i = rowEnd; i>= rowBegin; --i) { result[i][colBegin] = count; count++; } colBegin++; } return result; } };
相关文章推荐
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- 【leetcode】【59】Spiral Matrix II
- 【LeetCode】C# 59、Spiral Matrix II
- 【leetcode】59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- [LeetCode]59. Spiral Matrix II
- 【LeetCode】(59)Spiral Matrix II(Medium)
- leetcode 59. Spiral Matrix II
- LeetCode 54/59. Spiral Matrix i, ii
- [LeetCode]59 Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- [LeetCode] 59. Spiral Matrix II
- LeetCode(59)SPiral Matrix II
- [C语言][LeetCode][59]Spiral Matrix II
- 【leetcode】59.Spiral Matrix II
- LeetCode(59)SPiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- LeetCode_59---Spiral Matrix II