• 控制台打印螺旋数组


    最近园里面在聊打印螺旋数组,我业余写了一个自己的实现,如下:
     
    代码
    static void Main(string[] args)
            {
                
    int n = 0;

                
    try
                {
                    n 
    = Convert.ToInt32(Console.ReadLine());
                }
                
    catch {
                    Console.WriteLine(
    "Error");
                }

                
    int[,] arr = new int[n, n];

                Spiral(n, arr);

                PrintMatrix(n, arr);

                Console.ReadLine();
            }

            
    //螺旋数组
            public static void Spiral(int n,int[,] matrix)
            {
                
    int i = 0, j = 0, m = 0, k = 0;

                
    for (m = 0; m < n; m++)
                {

                    
    //方向→
                    for (i = m, j = m; j < n - m; j++)
                    {
                        matrix[i, j] 
    = ++k;
                    }
                    j
    --;
                    
                    
    //方向↓
                    for (i = i + 1; i < n - m; i++)
                    {
                        matrix[i, j] 
    = ++k;
                    }
                    i
    --;

                    
    //方向←
                    for (j = j - 1; j >= m; j--)
                    {
                        matrix[i, j] 
    = ++k;
                    }
                    j
    ++;


                    
    //方向↑
                    for (i = i - 1; i > m; i--)
                    {
                        matrix[i, j] 
    = ++k;
                    }
                    i
    ++;
                }
            }

           
            
    //打印
            public static void PrintMatrix(int n,int[,] matrix)
            {
                
    for (int a = 0; a < n; a++)
                {
                    
    for (int b = 0; b < n; b++)
                    {
                        
    if (matrix[a, b] < 10)
                        {
                            Console.Write(
    "0{0} ", matrix[a, b]);
                        }
                        
    else
                        {
                            Console.Write(
    "{0} ", matrix[a, b]);
                        }
                    }
                    Console.WriteLine();
                }
            }
  • 相关阅读:
    从一道比较奇葩的笔试题说起
    如何用一个语句判断一个整数是不是二的整数次幂——从一道简单的面试题浅谈C语言的类型提升(type promotion)
    C指针(转)
    raspberry-常用命令
    raspberry-同路由器用putty和vnc桌面登录方法
    结对编程-黄金点游戏
    软件工程第一次作业
    Python机器学习(9)——聚类算法之K均值
    Python机器学习(8)——推荐算法之推荐矩阵
    Python机器学习(7)——SVM支持向量机
  • 原文地址:https://www.cnblogs.com/Kurodo/p/1688586.html
Copyright © 2020-2023  润新知