Spiral Matrix——螺旋矩阵
private static void PrintSpiral () { int number = 3; int[,] spiralArr = Spiral(number); for (int i = 0; i < number; i++) { for (int j = 0; j < number; j++) { Console.Write(spiralArr[i, j] + " "); } Console.Write("\n"); } } static int[,] Spiral ( int number ) { var position = new { x = -1, y = 0 }; var directions = new[] { new { x = 1, y = 0 }, new { x = 0, y = 1 }, new { x = -1, y = 0 }, new { x = 0, y = -1 } }; var sequence = ( from n in Enumerable.Range(1, number) from o in Enumerable.Repeat(n, n != number ? 2 : 1) select o ).Reverse().ToList(); var result = new int[number, number]; int currentValue = 1; for (int i = 0; i < sequence.Count; i++) { var direction = directions[i % directions.Length]; for (int j = 0; j < sequence[i]; j++) { position = new { x = position.x + direction.x, y = position.y + direction.y }; result[position.y, position.x] = currentValue; currentValue++; } } return result; }
--
Scott,
Programmer in Beijing
[If you can’t explain it to a six year old, you don’t understand it yourself. —Albert Einstein ]