上一篇文章:KVO浅析与实例
转载请注明本文章出处:http://www.androiddev.net/
螺旋矩阵
什么是螺旋矩阵?以n=4为例,其输出结果为:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
这就是所谓的螺旋矩阵。
实现代码:
[code lang=”cpp”]
#include <iostream>
#include <iomanip>
using namespace std;
int map[100][100];
void go(int &p,int &state,int &i,int &j){
switch (state) {
case 0:{
if(map[i][j+1]!=-1&&map[i][j+1]==0){
map[i][j++]=p++;
}else{
map[i++][j]=p++;
state=1;
}
}break;case 1:{
if(map[i+1][j]!=-1&&map[i+1][j]==0){
map[i++][j]=p++;
}else{
map[i][j–]=p++;
state=2;
}
}break;case 2:{
if(map[i][j-1]!=-1&&map[i][j-1]==0){
map[i][j–]=p++;
}else{
map[i–][j]=p++;
state=3;
}
}break;case 3:{
if(map[i][j]!=-1&&map[i-1][j]==0){
map[i–][j]=p++;
}else{
map[i][j++]=p++;
state=0;
}
}break;
default:
break;
}
}
int main(int argc, const char * argv[])
{
int n=0;
memset(map, 0, sizeof(map));
cin>>n;
if(n>=100){
cout<<"error"<<endl;
return -1;
}
for(int i=0;i<n+2;i++){
map[0][i] = -1;
map[n+1][i] = -1;
map[i][0] = -1;
map[i][n+1] = -1;
}
for(int p=1,i=1,j=1,state=0;p<=n*n;){
go(p,state,i,j);
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
{
cout<<setw(3)<<map[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
[/code]
结果: