leetcode 81: Spiral Matrix II
来源:互联网 发布:python的readline 编辑:程序博客网 时间:2024/05/18 15:05
Spiral Matrix IIMar 28 '12
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 ]]
public class Solution { public int[][] generateMatrix(int n) { // Start typing your Java solution below // DO NOT write main() function int[][] res = new int[n][n]; if(n<1) return res; int top=0, bottom=n-1, left=0, right=n-1; int loop = (n+1)/2; for(int i=0, seq=1; i<loop; i++) { for(int j=left; j<=right; j++) { res[top][j] = seq++; } top++; if(top>bottom) return res; for(int j=top; j<=bottom; j++) { res[j][right] = seq++; } right--; if(left>right) return res; for(int j=right; j>=left; j--) { res[bottom][j] = seq++; } bottom--; if(top>bottom) return res; for(int j=bottom; j>=top; j--) { res[j][left] = seq++; } left++; } return res; }}
class Solution {public: vector<vector<int> > generateMatrix(int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> element(n, 0); vector<vector<int> > matrix(n, element); int lb = 0, rb = n-1, ub = 0, bb = n-1; for(int i=1; i<=n*n; ) { //up bound for(int i1=lb; i1<=rb; i1++) { matrix[ub][i1] = i++; } ++ub; if(i>n*n) return matrix; for(int i2=ub; i2<=bb; i2++) { matrix[i2][rb] = i++; } --rb; if(i>n*n) return matrix; for(int i3=rb; i3>=lb; i3--) { matrix[bb][i3] = i++; } --bb; if(i>n*n) return matrix; for(int i4=bb; i4>=ub; i4--) { matrix[i4][lb] = i++; } ++lb; } return matrix; }};
- leetcode 81: 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
- Leetcode: Spiral Matrix II
- leetcode 80: Spiral Matrix
- JAVA JTextField 只能输入小数(完美)//
- 专业程序员必知的技巧:敲打代码
- 390. Teach others by your example. 躬亲示范
- android下使用google test入门
- leetcode 81: Spiral Matrix II
- java运算符的结合性和优先级
- SQL查找删除重复行
- win7 64位系统web项目导出Excel问题汇总
- 四川省崇州市反贪局局长柯建国坠楼身亡
- 俄罗斯陨石坠落伤者超过100人
- 获取所有用户名 sql server
- B-Tree索引
- 如何成为强大的程序员?