- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Sea1
- {
- public class Position
- {
- public Position()
- {
- x = 0;
- y = 0;
- }
- public int x;
- public int y;
- }
- public class Direction
- {
- protected Position m_step = new Position();
- public Position Step(Position current)
- {
- Position pos = new Position();
- pos.x = current.x + m_step.x;
- pos.y = current.y + m_step.y;
- return pos;
- }
- public bool NeedTurn(Position current, int margin)
- {
- Position pos = Step(current);
- return ((Math.Abs(pos.x) > margin) || (Math.Abs(pos.y) > margin));
- }
- }
- public class Up: Direction
- {
- public Up()
- {
- m_step.x = 0;
- m_step.y = -1;
- }
- }
- public class Down: Direction
- {
- public Down()
- {
- m_step.x = 0;
- m_step.y = 1;
- }
- }
- public class Right: Direction
- {
- public Right()
- {
- m_step.x = 1;
- m_step.y = 0;
- }
- }
- public class Left: Direction
- {
- public Left()
- {
- m_step.x = -1;
- m_step.y = 0;
- }
- }
- public class Question4
- {
- int count;
- int[][] array;
- Position m_current = new Position();
- List<Direction> m_Directions = new List<Direction>();
- int m_index;
- public Question4(int n)
- {
- count = n;
- array = new int[2*n+1][];
- for (int i = 0; i<2*n+1; i++)
- {
- array[i] = new int[2*n+1];
- }
- m_Directions.Add(new Down());
- m_Directions.Add(new Right());
- m_Directions.Add(new Up());
- m_Directions.Add(new Left());
- m_index = 3;
- }
- public void Compute()
- {
- array[count][count] = 1;
- for (int i = 2; i <= (2 * count + 1) * (2 * count + 1); i++)
- {
- int margin = ((int)Math.Sqrt(i - 1) - 1)/2 + 1;
- if (m_Directions[m_index].NeedTurn(m_current, margin))
- {
- m_index = (m_index + 1) % m_Directions.Count;
- }
- m_current = m_Directions[m_index].Step(m_current);
- array[m_current.x + count][m_current.y + count] = i;
- }
- for (int j = 0; j < 2 * count + 1; j++)
- {
- for (int k = 0; k < 2 * count + 1; k++)
- {
- Console.Write(array[k][j].ToString("00"));
- Console.Write(" ");
- }
- Console.WriteLine(" ");
- Console.WriteLine(" ");
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/030420132717.html
来源: http://www.codesnippet.cn/detail/030420132717.html