Leetcode Spiral Matrix II
2015-10-20 00:06
453 查看
Leetcode Spiral Matrix II 相关代码,本代码重用了Spiral Matrix 的相关代码。以下给出可运行代码,以及测试:
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<vector<int> > generateMatrix(int n) { // Record the four sides offset, 0: right, 1: down, 2: left, 3: up vector<int> direction(4, 0); vector<vector<int> > re(n, vector<int>(n, 0)); // foo control the four conditions of moving int foo = 0; // x, y record the current positon in matrix int x = 0; int y = -1; int x_len = n; int y_len = n; int cur = 1; while (direction[1] + direction[3] != n) { switch(foo) { // left-->right case 0: y ++; for (; y < y_len - direction[foo]; y ++) { re[x][y] = cur ++; } y --; direction[3] ++; break; // up-->down case 1: x ++; for (; x < x_len - direction[foo]; x ++) { re[x][y] = cur ++; } x --; direction[0] ++; break; // right-->left case 2: y --; for (; y >= direction[foo]; y --) { re[x][y] = cur ++; } y ++; direction[1] ++; break; // down-->up case 3: x --; for (; x >= direction[foo]; x --) { re[x][y] = cur ++; } x ++; direction[2] ++; break; } foo = (++foo) % 4; } return re; } }; int main(int argc, char* argv[]) { Solution so; vector<vector<int> > re = so.generateMatrix(atoi(argv[1])); for (int i = 0; i < re.size(); i ++) { for (int j = 0; j < re[0].size(); j ++) { cout<<re[i][j]<<" "; } cout<<endl; } return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解