lkjjk

导航

C#螺旋矩阵,终于写出来了

 1 using System;
 2 
 3 namespace lx
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             Console.WriteLine("输入行数");
10             int row = int.Parse(Console.ReadLine());
11             Console.WriteLine("输入列数");
12             int column = int.Parse(Console.ReadLine());
13             int[,] array = new int[row, column];
14             int sum = row * column;
15             Console.WriteLine();
16             Print(0, 0, 1, row, column, sum, ref array);
17             Write(ref row, ref column, ref array);
18             Console.ReadKey();
19         }
20         public static void Write(ref int row, ref int column, ref int[,] array)
21         {
22             for (int i = 0; i < row; i++)
23             {
24                 for (int j = 0; j < column; j++)
25                 {
26                     if (array[i, j] < 10)
27                     {
28                         Console.Write(array[i, j] + "    ");
29                     }
30                     else if (array[i, j] < 100)
31                     {
32                         Console.Write(array[i, j] + "   ");
33                     }
34                     else if (array[i, j] < 1000)
35                     {
36                         Console.Write(array[i, j] + "  ");
37                     }
38                     else
39                     {
40                         Console.Write(array[i, j] + " ");
41                     }
42                 }
43                 Console.WriteLine();
44             }
45         }
46         public static void Print(int x, int y, int num, int row, int column, int sum, ref int[,] array)
47         {
48             int i,j;
49             ///
50             for (j = y; j < column && array[x, j] == 0 && num <= sum; j++)
51             {
52                 array[x, j] = num++;
53                 y = j;
54             }
55             x++;
56             //
57             for (i = x; i < row && array[i, y] == 0 && num <= sum; i++)
58             {
59                 array[i, y] = num++;
60                 x = i;
61             }
62             y--;
63             //
64             for (j = y; j >= 0 &&x>=0&& array[x, j] == 0 && num <= sum; j--)
65             {
66                 array[x, j] = num++;
67                 y = j;
68             }
69             x--;
70             //
71             for (i = x; i >= 0 &&y>=0&& array[i, y] == 0 && num <= sum; i--)
72             {
73                 array[i, y] = num++;
74                 x = i;
75             }
76             if (num > sum)//到最大值结束程序
77             {
78                 return;
79             }
80             else
81             {
82                 Print(x, y + 1, num, row, column, sum, ref array);
83             }
84         }
85     }
86 }

 

posted on 2020-11-28 16:54  lkjjk  阅读(237)  评论(0)    收藏  举报