螺旋矩阵 递归算法

public class Test2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(cal(i, j, 5)+"\t");
            }
            System.out.println();
        }
    }

    static int cal(int row, int col, int n) {
        if (row == 0)
            return col + 1;
        if (col == n - 1)
            return (n - 1) + (row + 1);
        if (row == n - 1)
            return 2 * (n - 1) + (n - col);
        if (col == 0)
            return 3 * (n - 1) + (n - row);

        return (n - 1) * 4 + cal(row - 1, col - 1, n - 2);
    }
}
 

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