今天看到一位网友碰到的一道面试题目,觉得挺有意思的,就写了一下算法:
题目:打印下面这个矩阵
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
代码如下:class program { static void Main(string[] args) { new program().Run(); }
//各方向环绕的次数
int right = 1; int down = 0; int left = 0; int up = 0;
int n = 6; //矩阵 N*N
//矩阵行与列
int row = 0; int col = 0;
Direction direction = Direction.Right; int[,] a = new int[6, 6];
enum Direction { Right = 0, Down = 1, Left = 2, Up = 3 }
void Run() { for (int i = 1; i <= n * n; i++) { a[row, col] = i; Fang(); }
for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { Console.Write(" {0} ", a[i, j]); }
Console.Write("\n"); }
Console.Read(); }
void Fang() { switch (direction) { case Direction.Right: if (col < n - down - 1) { col++; } else { direction = Direction.Down; row++; down++; } break; case Direction.Down: if (row < n - left - 1) { row++; } else { direction = Direction.Left; col--; left++; } break; case Direction.Left: if (col > up) { col--; } else { direction = Direction.Up; up++; row--; } break; case Direction.Up: if (row > right) { row--; } else { direction = Direction.Right; right++; col++; } break; } } }
posted on 2010-11-12 17:06 Macou 阅读(529) 评论(3) 编辑 收藏 举报
Powered by: 博客园 Copyright © 2024 Macou Powered by .NET 9.0 on Kubernetes