一个打印螺旋数的程序
生活随笔
收集整理的這篇文章主要介紹了
一个打印螺旋数的程序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看到博客園上有人發這個程序的練習,便自己也寫了一個。
代碼 ?1?class?ScremNumbers?2?{
?3?????enum?Direction?{?Right,?Down,?Left,?Up?}
?4?
?5?????[System.Diagnostics.DebuggerDisplay("({X},{Y})")]
?6?????struct?Point
?7?????{
?8?????????public?int?X;
?9?????????public?int?Y;
10?????}
11?
12?????public?int?Count?{?get;?private?set;?}
13?
14?????int[,]?numbers;
15?????public?ScremNumbers(int?count)
16?????{
17?????????this.Count?=?count;
18?????????numbers?=?new?int[count,?count];
19?
20?????????Process();
21?????}
22?
23?????void?Process()
24?????{
25?????????var?point?=?new?Point();
26?????????var?direction?=?Direction.Right;
27?
28?????????for?(int?i?=?0;?i?<?Count?*?Count;?i++)
29?????????{
30?????????????var?nextPoint?=?NextPoint(point,?direction);
31?????????????if?(this[nextPoint]?!=?0)
32?????????????{
33?????????????????direction?=?NextDirection(direction);
34?????????????????nextPoint?=?NextPoint(point,?direction);
35?????????????}
36?
37?????????????this[point]?=?i?+?1;
38?????????????point?=?nextPoint;
39?????????}
40?????}
41?
42?????public?void?Print()
43?????{
44?????????var?maxLength?=?(Count?*?Count).ToString().Length?+?1;
45?
46?????????for?(int?i?=?0;?i?<?Count;?i++)
47?????????{
48?????????????for?(int?j?=?0;?j?<?Count;?j++)
49?????????????{
50?????????????????Console.Write(numbers[j,?i].ToString().PadRight(4));
51?????????????}
52?????????????Console.WriteLine();
53?????????}
54?????}
55?
56?????Point?NextPoint(Point?point,?Direction?direction)
57?????{
58?????????var?nextPoint?=?point;
59?????????switch?(direction)
60?????????{
61?????????????case?Direction.Right:
62?????????????????nextPoint.X++;
63?????????????????break;
64?????????????case?Direction.Down:
65?????????????????nextPoint.Y++;
66?????????????????break;
67?????????????case?Direction.Left:
68?????????????????nextPoint.X--;
69?????????????????break;
70?????????????case?Direction.Up:
71?????????????????nextPoint.Y--;
72?????????????????break;
73?????????????default:
74?????????????????throw?new?InvalidOperationException();
75?????????}
76?
77?????????return?nextPoint;
78?????}
79?
80?????Direction?NextDirection(Direction?direction)
81?????{
82?????????return?(Direction)(((int)direction?+?1)?%?4);
83?????}
84?
85?????private?int?this[Point?index]
86?????{
87?????????get
88?????????{
89?????????????if?(index.X?<?0?||?index.X?>=?Count?||?index.Y?<?0?||?index.Y?>=?Count)
90?????????????????return?-1;
91?
92?????????????return?numbers[index.X,?index.Y];
93?????????}
94?
95?????????set?{?numbers[index.X,?index.Y]?=?value;?}
96?????}
97?}
?
程序用的算法比較簡單,是一種最直接的算法:不停的往前走,碰壁便轉彎。總體感覺整體思路還比較清晰,這里記錄一下。
?
轉載于:https://www.cnblogs.com/TianFang/archive/2010/12/27/1918330.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的一个打印螺旋数的程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 十六进制字符串与数值类型之间转换
- 下一篇: 文档评审管理简介