螺旋矩阵的实现推广

using System;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            printMatrix(4,2);
            System.Console.Read();
        }
        public static int min(int i, int j)
        {
            return i <= j ? i : j;
        }
        public static void printMatrix(int m,int n)
        {
            for (int i = 1; i <= m; i++)
            {
                for (int j = 1; j <= n; j++)
                {
                    int k = min(min(min(i, j), min(m + 1 - i, j)), min(i, n + 1 - j));
                    int sum = 0;
                    if (k > 1)
                    {
                        for (int v = 1; v < k; v++)
                            sum = sum + 2 * (m+1+n + 1 - 4 * v);
                    }
                    if (i==k&&j>=k&&j<=n+1-k) 
                        System.Console.Write("{0,5} ", sum + j - k + 1);
                    else if (j==n+1-k&&i>k&&i<=m+1-k )
                        System.Console.Write("{0,5} ", sum + n + 1 - 2 * k + i - k + 1);
                    else if (i==m+1-k && j>=k&& j<n+1-k )
                        System.Console.Write("{0,5} ", sum + (m+1+n + 1 - 4 * k) + n + 2 - k - j);
                    else if (j==k&&i>k&&i<m+1-k)
                        System.Console.Write("{0,5} ", sum + (m+1+2*(n + 1) - 6 * k) + m + 2 - k - i);                }
                System.Console.WriteLine();
            }
        } 
    }
   
}

你可能感兴趣的:(J#)