2018年8月21日 星期二

itsa65 3螺旋矩陣

#include<iostream>
using namespace std;

int main()
{
int size, direction, x, y, tx, ty, num, finish;
char c;
int arr[32][32];
int cw[4][2] = { { 0,1 },{ 1,0 },{ 0,-1 },{ -1,0 } };
int cc[4][2] = { { 1,0 },{ 0,1 },{ -1,0 },{ 0,-1 } };
while (cin >> size >> c >> direction)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
arr[i][j] = 0;
x = y = tx = ty = finish = 0;
num = 2;
arr[0][0] = 1;
if (direction == 1)
{
for (int i = 0; i <= size / 2; i++)
{
for (int j = 0; j < 4; j++)
{
if (!finish)
{
for (int k = 1; k < size; k++)
{
if (arr[x + cw[j][0] * k][y + cw[j][1] * k] == 0)
{
arr[x + cw[j][0] * k][y + cw[j][1] * k] = num;
tx = x + cw[j][0] * k;
ty = y + cw[j][1] * k;
if (num == size * size)
{
finish = 1;
break;
}
num++;
}
else
break;
}
}
x = tx;
y = ty;
}
}
}
else
{
for (int i = 0; i <= size / 2; i++)
{
for (int j = 0; j < 4; j++)
{
if (!finish)
{
for (int k = 1; k < size; k++)
{
if (arr[x + cc[j][0] * k][y + cc[j][1] * k] == 0)
{
arr[x + cc[j][0] * k][y + cc[j][1] * k] = num;
tx = x + cc[j][0] * k;
ty = y + cc[j][1] * k;
if (num == size * size)
{
finish = 1;
break;
}
num++;
}
else
break;
}
}
x = tx;
y = ty;
}
}
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (j > 0)
cout << ",";
if (arr[i][j] < 10)
cout << "00" << arr[i][j];
else if (arr[i][j] < 100)
cout << "0" << arr[i][j];
else
cout << arr[i][j];
}
cout << endl;
}
}
return 0;
}

沒有留言:

張貼留言