SHOW:
|
|
- or go back to the newest paste.
| 1 | using System; | |
| 2 | ||
| 3 | class SpiralMatrix | |
| 4 | {
| |
| 5 | static void Main() | |
| 6 | {
| |
| 7 | int n = int.Parse(Console.ReadLine()); | |
| 8 | int[,] spiral = new int[n, n]; | |
| 9 | int count = 1; | |
| 10 | int row = 0; | |
| 11 | int col = -1; | |
| 12 | ||
| 13 | for (int k = 0; k <= n / 2; k++) | |
| 14 | {
| |
| 15 | //right | |
| 16 | for (col = col + 1; col <= n - 1 - k; col++) | |
| 17 | {
| |
| 18 | spiral[row, col] = count; | |
| 19 | if (count == n * n) | |
| 20 | goto print; | |
| 21 | count++; | |
| 22 | } | |
| 23 | col--; | |
| 24 | //down | |
| 25 | for (row = row + 1; row <= n - 1 - k; row++) | |
| 26 | {
| |
| 27 | spiral[row, col] = count; | |
| 28 | if (count == n * n) | |
| 29 | goto print; | |
| 30 | count++; | |
| 31 | } | |
| 32 | row--; | |
| 33 | //left | |
| 34 | for (col = col - 1; col >= k; col--) | |
| 35 | {
| |
| 36 | spiral[row, col] = count; | |
| 37 | if (count == n * n) | |
| 38 | goto print; | |
| 39 | count++; | |
| 40 | } | |
| 41 | col++; | |
| 42 | //up | |
| 43 | for (row = row - 1; row > k; row--) | |
| 44 | {
| |
| 45 | spiral[row, col] = count; | |
| 46 | if (count == n * n) | |
| 47 | goto print; | |
| 48 | count++; | |
| 49 | } | |
| 50 | row++; | |
| 51 | } | |
| 52 | print: | |
| 53 | for (row = 0; row < n; row++) | |
| 54 | {
| |
| 55 | for (col = 0; col < n; col++) | |
| 56 | {
| |
| 57 | Console.Write("{0,4}", spiral[row, col]);
| |
| 58 | } | |
| 59 | Console.WriteLine(); | |
| 60 | } | |
| 61 | } | |
| 62 | } |