题解 | #螺旋矩阵(二)#

螺旋矩阵(二)

http://www.nowcoder.com/practice/2c8078a728834e81a046fdefdea049aa

import java.util.*;


public class Solution {

    public int num = 1;

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param n int整型
     * @return int整型二维数组
     */
    public int[][] Matrix (int n) {
        // write code here
        int tR = 0;
        int tC = 0;
        int dR = n - 1;
        int dC = n - 1;
        int[][] matrix = new int[n][n];
        while (tR <= dR && tC <= tR) {
            process(matrix, tR++, tC++, dR--, dC--);
        }
        return matrix;
    }

    public void process(int[][] matrix, int a, int b, int c, int d) {
        if (a == c) {
            for (int i = b; i <= d; i++) {
                matrix[a][i] = num;
                num++;
            }
        } else if (b == d) {
            for (int i = a; i <= c; i++) {
                matrix[i][b] = num;
                num++;
            }
        } else {
            int curC = b;
            int curR = a;
            while (curC != d) {
                matrix[a][curC] = num;
                num++;
                curC++;
            }
            while (curR != c) {
                matrix[curR][d] = num;
                num++;
                curR++;
            }
            while (curC != b) {
                matrix[c][curC] = num;
                num++;
                curC--;
            }
            while (curR != a) {
                matrix[curR][b] = num;
                num++;
                curR--;
            }
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
挣K存W养DOG:他真的很中意你,为什么不回他
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务