c# 螺旋矩陣

keeking發表於2012-06-15
static void Main(string[] args)
        {
           int i, j;  
//         int n=15;  
           int n=9;  
           int[,] matrix = new int[n,n]; //螺旋矩陣(二維陣列)  
             
           SetMatrix(matrix, 0, 0, 1, n); 
      
           //列印螺旋矩陣 
           for(i = 0; i < n; i++) {
               for (j = 0; j < n; j++)
               {
                   Console.Write("{0, 3}", matrix[i, j]);
                   //Console.Write(" ");
               }
                  Console.WriteLine(); 
        }
            Console.Read();
    }

        private static void SetMatrix(int[,] matrix, int x, int y, int start, int n)
        {
            int i, j;
            if (n < 0) { return; }
            if (n == 1)
            {
                matrix[x,y] = start;
                return;
            }
            for (i = y; i < y + n - 1; i++)          /* 上部 */
                matrix[x,i] = start++;
            for (j = x; j < x + n - 1; j++)          /* 右邊 */
                matrix[j,y + n - 1] = start++;
            for (i = y + n - 1; i > y; i--)              /* 底部 */
                matrix[x + n - 1,i] = start++;
            for (j = x + n - 1; j > x; j--)              /* 左邊 */
                matrix[j,y] = start++;
            SetMatrix(matrix, x + 1, y + 1, start, n - 2);     /* 遞迴 */
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7899089/viewspace-732993/,如需轉載,請註明出處,否則將追究法律責任。

相關文章