读书人

旋转方阵解决方法

发布时间: 2012-02-27 10:00:22 作者: rapoo

旋转方阵
Description

打印出一个旋转方阵,见Sample Output.

Input

输入一个整数n(1 <= n <= 20), n为方阵的行数。

Output

输出一个大小为n*n的距阵

Sample Input


5

Sample Output


1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9

Hint

输出控制:每个数字占4位,居左。
cout < < setw(4) < < setiosflags(ios::left) < < a[i][j];


[解决办法]
// tt.cpp : Defines the entry point for the console application.
//


#include "iostream "
#include "iomanip "

using namespace std;

void temperatures(const double Fahrenheit, double& celsius, double& kelvin) {

celsius = 1.8 * Fahrenheit + 32;
kelvin = celsius + 273.16;
}

void printf_rmatrix(int raw) {

if (raw < 0)
return;

int** arry = new int*[raw];
for(int i = 0; i < raw; ++i)
arry[i] = new int[raw];

for (int x = 0; x < raw; ++x)
for (int y = 0; y < raw; ++y)
arry[x][y] = 0;

int tick = 1;
int x = 0;
int y = 0;
int state = 0;

while (true) {

arry[x][y] = tick++;

if (state == 0) {
if (x + 1 < raw && arry[x + 1][y] == 0)
x++;
else if (y + 1 < raw && arry[x][y + 1] == 0) {
y++;
state = 1;
}
else
break;
}
else if (state == 1) {
if (y + 1 < raw && arry[x][y + 1] == 0)
y++;
else if (x - 1 > = 0 && arry[x - 1][y] == 0) {
x--;
state = 2;
}
else
break;
}
else if (state == 2) {
if (x - 1 > = 0 && arry[x - 1][y] == 0)
x--;
else if (y - 1 > = 0 && arry[x][y - 1] == 0) {
y--;
state = 3;
}
else
break;
}
else if (state == 3) {
if (y - 1 > = 0 && arry[x][y - 1] == 0)
y--;
else if (x + 1 < raw && arry[x + 1][y] == 0) {
x++;
state = 0;
}
else
break;

}
else
break;

}

for (int x = 0; x < raw; ++x)
{
for (int y = 0; y < raw; ++y)
cout < < setw(4) < < setiosflags(ios::left) < < arry[x][y];
cout < <endl;
}

for(int i = 0; i < raw; ++i)
delete[] arry[i];
delete[] arry;

}

void main()
{
printf_rmatrix(10);



return;

}

[解决办法]
仅供参考

void matrix(int n) {
int row = 0, col = 0, rstep = 1, cstrp = 1;
int flag = 0;
int m[n][n];
for (int i=1; i <=n*n; i++) {
if (flag == 0) {
if (rstep == 1) {
m[row++][col] = i;
if (row == n-col) {
col++;
rstep = -1;
flag = 1;
}
} else {
m[--row][col-1] = i;
if (row == n-col) {
col--;
rstep = 1;
flag = 1;
}
}
} else {
if (cstep == 1) {
m[row-1][col++] = i;
if (col == row) {
row--;
cstep = -1;
flag = 0;
}
} else {
m[row][--col] = i;
if (col-1 == row) {
row++;
cstep = 1;
flag = 0;
}
}
}
}

for (int i=0; i <n; i++) {
for (int j=0; j <n; j++) {
cout < < setw(4) < < setiosflags(ios::left) < < m[i][j];
}
}
}

void main(void) {
int n = 0;
cou < < "Intput: ";
cin > > n;
matrix(n);
}

读书人网 >C++

热点推荐