首页 > 代码库 > Spiral Matrix II
Spiral Matrix II
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 ]]
C++实现代码:(注意奇数和偶数的不同)
#include<iostream>#include<vector>using namespace std;class Solution{public: vector<vector<int> > generateMatrix(int n) { if(n==0) return vector<vector<int> >(); vector<vector<int> > vec(n,vector<int>(n)); int i,j; int count=1; i=0,j=0; while(((n%2)&&(count<n*n))||((n%2==0)&&(count<=n*n))) { for(; j<n-i-1; j++) { vec[i][j]=count; count++; } for(; i<j; i++) { vec[i][j]=count; count++; } for(; j>n-i-1; j--) { vec[i][j]=count; count++; } for(; i>j; i--) { vec[i][j]=count; count++; } i++; j++; } if(n%2) vec[i][j]=count; return vec; }};int main(){ Solution s; vector<vector<int> > result=s.generateMatrix(4); for(auto a:result) { for(auto v:a) cout<<v<<" "; cout<<endl; } cout<<endl;}
Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。