LeetCode | 59. Spiral Matrix II
来源:互联网 发布:淘宝网原味内裤 编辑:程序博客网 时间:2024/06/05 20:42
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:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
题意:填充蛇形矩阵
class Solution {public:/* 蛇形矩阵*/ vector<vector<int>> generateMatrix(int n) { vector<vector<int> > matrix; int temp = 0; for(int i=0;i<n;i++) { vector<int> line; for(int j=0;j<n;j++) { line.push_back(temp); } matrix.push_back(line); } vector<int> res; int x = 0, y = 0, tot = 1; //tot用于计数,作为停止条件 int up = 0, down = n-1, left = 0, right = n-1; if(n==0) //错误输入数据,特殊处理 return matrix; //开始遍历 while(tot <= n*n) { while(x==up && tot <= n*n) //最上面一行 { matrix[x][y] = tot; tot++; if(y == right) x++; else y++; } up += 1; while(y==right && tot <= n*n) { matrix[x][y] = tot; tot++; if(x == down) y--; else x++; } right -= 1; while(x==down && tot <= n*n) { matrix[x][y] = tot; tot++; if(y == left) x--; else y--; } down -= 1; while(y==left && tot <= n*n) { matrix[x][y] = tot; tot++; if(x == up) y++; else x--; } left += 1; } //cout<<up<<down<<left<<right; return matrix; }};
附上solution区代码:
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > ret( n, vector<int>(n) ); int k = 1, i = 0; while( k <= n * n ) { int j = i; // four steps while( j < n - i ) // 1. horizonal, left to right ret[i][j++] = k++; j = i + 1; while( j < n - i ) // 2. vertical, top to bottom ret[j++][n-i-1] = k++; j = n - i - 2; while( j > i ) // 3. horizonal, right to left ret[n-i-1][j--] = k++; j = n - i - 1; while( j > i ) // 4. vertical, bottom to top ret[j--][i] = k++; i++; // next loop } return ret; } };
阅读全文
1 0
- [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
- 59. Spiral Matrix II LeetCode
- [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
- 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
- [leetcode] 59. Spiral Matrix II
- [leetcode]59. Spiral Matrix II
- Jquery 如何限制用户输入数据必须为数字判断
- myeclipse2014设置热部署
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.
- BootStrap自定义小图标
- merge-two-sorted-lists
- LeetCode | 59. Spiral Matrix II
- java的Collections.sort集合排序
- 分享一个非常不错的E文图书网
- PHP Mailer邮件发送失败发送失败! Mailer Error: SMTP connect() failed.
- Unity3D 11-SceneManager场景管理用法总结
- sql_log_bin在GTID复制下的一个现象
- mysql存储过程中截取拼接的字符串
- Javascript之BOM与DOM讲解
- 一个很有用的图像处理工具箱