输出:
1 3 4 10
2 5 9 11
6 8 12 15
7 13 14 16
请问如何实现?
提供个思路
谢谢
[QUOTE]#include<iostream>
#include<iomanip>
using namespace std;
void main()//运行环境VC6.0++(测试通过)
{
const int N = 4;//由于本人还没有学动态数组,所以只能这样了,可以改下这个值:5,6,7……
int i = 0, j = 0;
int count = 1;
int Array[N][N];
bool up = true;
for (;i + j < 2*N - 2;) //控制数据的移动
{
if (count == 1)
{}
else
if (up)//上移
{
Array[i++][j--] = count++;
for (;i >= 0 && i < N - 1 && j > 0 && j < N - 1;)
{
Array[i++][j--] = count++;
}
}
else//下移
{
Array[i--][j++] = count++;
for (;i > 0 && i < N - 1 && j >= 0 && j < N - 1;)
{
Array[i--][j++] = count++;
}
}
if ((j == 0 && i != N - 1) || j == N - 1)//边缘情况
{
Array[i++][j] = count++;
up = !up;
}
else
{
Array[i][j++] = count++;
up = !up;
}
Array[i][j] = count;
}
for (i = 0;i < N;i++)//打印
{
for (j = 0;j < N;j++)
{
cout << setw(4) << Array[i][j];
}
cout << endl;
}
}
[CODE]#include <iostream>
using namespace std;
const int n = 4;
int main(){
int a[n][n];
int i = 0,j = 0,k = 1;
bool right_up = false;
while (k != n*n+1){
if (right_up){
for (;i >= 0 && j < n;--i,++j)
a[i][j] = k++;
right_up = false;
j == n ? --j,i+=2 : ++i;
}
else{
for (;j >= 0 && i < n;++i,--j)
a[i][j] = k++;
right_up = true;
i == n ? --i,j+=2 : ++j;
}
}
//display :
for (int i = 0;i < n;++i){
for (int j = 0;j < n;++j)
cout << a[i][j] << " ";
cout << endl;
}
system("pause");
}[/CODE]
写了哈!
在vc6.0