U E D R , A S I H C RSS

Spiral Array/세연&재니

작성자 페이지

세여니
02 장재니 Genie

소스

~cpp
#include <iostream>
#include <vector>
using namespace std;

vector< vector<int> > xbox;

void makeXbox(int, int);
void fillXbox(int, int);
void showXbox(int, int);

int main()
{
	int nRow, nCol;
	cin >> nRow;
	cin >> nCol;
	makeXbox(nRow, nCol);
	fillXbox(nRow, nCol);
	showXbox(nRow, nCol);
	return 0;
}

void makeXbox(int nRow, int nCol)
{
	xbox.resize(nRow + 2);
	for (int i = 0 ; i < nRow + 2 ; i++)
		xbox[i].resize(nCol + 2);
	for (i = 0 ; i < nRow + 2 ; i++)
		for (int j = 0 ; j < nCol + 2 ; j++)
			xbox[i][j] = ((i == 0 || i == nRow + 1 || j == 0 || j == nCol + 1) ? 0 : (nRow * nCol));
}

void fillXbox(int nRow, int nCol)
{
	int nRowState = 1, nColState = 1;
	int direction = 0, nextCell;
	int movement[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
	for (int i = 0 ; i < nRow * nCol ; i++)
	{
		xbox[nRowState][nColState] = i;
		nextCell = xbox[nRowState + movement[direction][0]][nColState + movement[direction][1]];
		if (nextCell != (nRow * nCol))
			direction = (direction + 1) % 4;
		nRowState += movement[direction][0];
		nColState += movement[direction][1];
	}
}

void showXbox(int nRow, int nCol)
{
	for (int i = 1 ; i <= nRow ; i++)
	{
		for (int j = 1 ; j <= nCol ; j++)
			cout << xbox[i][j] << "\t";
		cout << endl;
	}
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:28:05
Processing time 0.0087 sec