首页 > 代码库 > [leetcode]Spiral Matrix II
[leetcode]Spiral Matrix II
问题描述:
Given an integer n, generate a square matrix filled with elements from 1 ton2 in spiral order.
For example,
Given n = 3
,
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
基本思路:
本题是上一篇《Spiral Matrix》的变形。可以采用同样的遍历方法为其赋值,创建旋转矩阵。
代码:
vector<vector<int> > generateMatrix(int n) { //C++ vector<vector<int> >result; if(n <=0 ) return result; for(int i = 0; i < n; i++){ vector<int> tmp(n,0); result.push_back(tmp); } int rowBegin = 0; int rowEnd = n-1; int colBegin = 0; int colEnd = n-1; int count = 1; while(rowBegin <= rowEnd && colBegin <= colEnd){ //to right for(int j = colBegin; j <= colEnd; j++) result[rowBegin][j] =count++; rowBegin++; //to down for(int j = rowBegin; j <= rowEnd; j++) result[j][colEnd] = count++; colEnd--; //to left if(rowBegin <= rowEnd){ for(int j = colEnd; j >= colBegin; j--) result[rowEnd][j] = count++; } rowEnd--; //to up if(colBegin <= colEnd){ for(int j = rowEnd; j >= rowBegin; j--) result[j][colBegin] = count++; } colBegin++; } return result; }
[leetcode]Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。