题目描述
在n*n方阵里填入1,2,...,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
输入
直接输入方阵的维数,即n的值。(n<=100)
| 样例输入 3 |
输出
输出结果是蛇形方阵。
| 样例输出
7 8 1 6 9 2 5 4 3
|
时间限制C/C++语言:2000MS其它语言:4000MS | 内存限制C/C++语言:65536KB其它语言:589824KB |
#include<iostream>
#include<vector>
using namespace std;
int get_v(vector<vector<int> > &v, int loop, int size, int &count)
{
for (int i = loop; i < size - loop; i++)
{
v[i][size - loop - 1] = count;
count++;
}
if (count == size*size+1) return count;
for (int j = size - loop-1-1; j >=loop; j--)
{
v[size - loop - 1][j] = count;
count++;
}
if (count == size*size+1) return count;
for (int j = size - loop - 1 - 1; j >= loop; j--)
{
v[j][loop] = count;
count++;
}
if (count == size*size+1) return count;
for (int i = loop+1; i < size - loop-1; i++)
{
v[loop][i] = count;
count++;
}
return count;
}
int main()
{
int n;
while (cin >> n)
{
//int **A=new
int b[] = {1,2,3,4};
vector<vector<int> > v;
for (int i = 0; i < n; i++)
{
vector<int> temp(n,0);
v.push_back(temp);
}
int count = 1;
for (int j = 0;; j++)
{
if (count == n*n + 1) break;
get_v(v, j, n, count);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (j == n - 1) cout << v[i][j] << endl;
else
cout << v[i][j]<<" ";
}
}
}
}
# include <iostream>
using namespace std;
int main ()
{
int n;
while(cin>>n)
{
int A[100][100];
for (int i=0;i<100;i++)
{
for (int j=0;j<100;j++)
{
A[i][j]=0;
}
}
int x=0,y=n-1,num=1;
A[x][y]=num;
while(num<n*n)
{
while((x+1)<n && !A[x+1][y])
{
x++;
num++;
A[x][y]=num;
}
while((y-1)>=0 && !A[x][y-1])
{
y--;
num++;
A[x][y]=num;
}
while((x-1)>=0 && !A[x-1][y])
{
x--;
num++;
A[x][y]=num;
}
while((y+1)<n && !A[x][y+1])
{
y++;
num++;
A[x][y]=num;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<A[i][j];
if(j!=n-1)
{
cout<<' ';
}
}
cout<<endl;
}
}
}