snail.cpp
 1  #include <iostream>
 2  using namespace std;
 3  #include <iomanip>
 4  
 5  const int	MAX = 100;
 6  int	board[MAX][MAX] = {};
 7  int	N;
 8  
 9  void	printBoard(void)
10  {
11  	for (int y = 0; y < N; y++)
12  	{
13  		for (int x = 0; x < N; x++)
14  		{
15  			cout << setfill('0') << setw(2) << board[y][x] << " ";
16  		}
17  		cout << endl;
18  	}
19  }
20  
21  enum DIR
22  {
23  	RIGHT = 0,
24  	DOWN = 1,
25  	LEFT = 2,
26  	UP = 3,
27  };
28  
29  bool	canGo(int y, int x)
30  {
31  	if (y < 0 || y >= N)
32  		return false;
33  	if (x < 0 || x >= N)
34  		return false;
35  	if (board[y][x] != 0)
36  		return false;
37  	return true;
38  }
39  
40  void	setBoard(void)
41  {
42  	int dir = RIGHT;
43  	int num = 1;
44  	int y = 0;
45  	int x = 0;
46  
47  	int dy[] = {0, 1, 0, -1};
48  	int dx[] = {1, 0, -1, 0};
49  
50  	while (true)
51  	{
52  		board[y][x] = num;
53  		if (num == N * N)
54  			break;
55  		int nextY = y + dy[dir];
56  		int nextX = x + dx[dir];
57  		if (canGo(nextY, nextX))
58  		{
59  			y = nextY;
60  			x = nextX;
61  			num++;
62  		}
63  		else
64  			dir = (dir + 1) % 4;
65  	}
66  }
67  
68  int	main()
69  {
70  	cin >> N;
71  
72  	setBoard();
73  	printBoard();
74  	return (0);
75  }