LeetCode: Spiral Matrix II
来源:互联网 发布:mac pro 贴膜涂层脱落 编辑:程序博客网 时间:2024/05/01 05:42
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
class Solution {public: vector<vector<int> > generateMatrix(int n) { vector<int> temp(n, 0); vector<vector<int> > result(n, temp);max = n * n;if(n == 0)return result;print(0, n, 0, n, 0, 1, result);return result; }private:int max; void print(int startX, int endX, int startY, int endY, int turn, int value, vector<vector<int> > &result) { int x, y; if(startX >= endX || startY >= endY || value > max) return; turn = turn % 4; if(turn == 0) { y = startY; x = startX; while(y < endY) { result[x][y] = value; y++; value++; } print(startX + 1, endX, startY, endY, turn + 1,value, result); } else if(turn == 1) { y = endY - 1; x = startX; while(x < endX) { result[x][y] = value; x++;value++; } print(startX, endX, startY, endY - 1, turn + 1, value, result); } else if(turn == 2) { y = endY - 1; x = endX - 1; while(y >= startY) { result[x][y] = value; y--;value++; } print(startX, endX - 1, startY, endY, turn + 1, value, result); } else { y = startY; x = endX - 1; while(x >= startX) { result[x][y] = value; x--;value++; } print(startX, endX, startY + 1, endY, turn + 1, value, result); } }};
Round 2:
class Solution {public: vector<vector<int> > generateMatrix(int n) { int count = 1; vector<int> temp(n, 0); vector<vector<int> > result(n, temp); int x = 0, y = 0, carry = 0; while(count <= n*n) { while(x == carry && y < n-carry) { result[x][y] = count; count++; y++; } y--; x++; while(y == n-1-carry && x < n-carry) { result[x][y] = count; count++; x++; } x--; y--; while(x == n-1-carry && y >= carry) { result[x][y] = count; count++; y--; } y++; x--; while(y == carry && x > carry) { result[x][y] = count; count++; x--; } x++; y++; carry++; } return result; }};
0 0
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- Spiral Matrix II -- LeetCode
- Leetcode: Palindrome Partitioning
- stack--Longest Valid Parentheses
- Activity的task相关
- Ubuntu下tar.gz文件安装方法
- Java之WeakReference与SoftReference使用讲解
- LeetCode: Spiral Matrix II
- 《深度探索C++对象模型》第一章关于对象ObjectLessons之读书笔记
- Tian Ji -- The Horse Racing(杭电1052)(贪心)
- onvif学习1-框架介绍
- 【BZOJ】【P1492】【NOI2007】【货币兑换Cash】【题解】【cdq分治】
- onvif学习2-soap介绍以及gsoap使用
- 【暴力】POJ-3006 Dirichlet's Theorem on Arithmetic Progressions
- CKeditor 3.6.6.2 asp.net 使用与配置的整理
- test1