矩阵的蛇形填充

来源:互联网 发布:mac ssh 阿里云服务器 编辑:程序博客网 时间:2024/05/01 07:42

一个10介矩阵的蛇形填充

最后要达到如下效果:

以4X4矩阵为例:

1     2        6       7    .

3     5        8       13 

4     9        12     14

10   11     15     16

 

 

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace Number
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] House=new int[10,10];
            int direction = 1;//-1left,1 right
            int currnetNum = 1;
            int XPos = 0;
            int YPos = 0;
            int currnetStep = 0;
            while (true)
            {
                if (currnetStep==19)
                {
                    break;
                }
                int roolStep = currnetStep;
                if (currnetStep >= 10)
                {
                    roolStep = 18 - currnetStep;
                }
              
                for (int j = 0; j <= roolStep; j++)
                {
                    XPos = XPos - (j == 0 ? 0 : 1) * direction;
                    YPos = YPos + (j == 0 ? 0 : 1) * direction;
                    House[XPos, YPos] = currnetNum++;
                }
                if (XPos == 9)
                {
                    YPos++;
                }
                else if (YPos == 9)
                {
                    XPos++;
                }
                else if (YPos == roolStep && XPos == 0)
                {
                    YPos++;                 
                }
                else if (XPos == roolStep && YPos == 0)
                {
                    XPos++;                  
                }
                direction = -direction;
                currnetStep++;
               
            }
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    Console.SetCursorPosition(j * 5, i * 1);
                    Console.Write(House[i,j]);                  
                }               
            }
            Console.Read();
        }
    }
}