LeetCode ---- 54、螺旋矩阵

题目链接

思路:

相当于转圈打印。

用 tR,tC 和 dR,dC 来表示每一圈的左上角的坐标与右下角的坐标,接着只需要通过坐标来判断转圈的方向即可。

代码如下。

    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new ArrayList<>();
        }
        int tR = 0;   
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        List<Integer> ans = new ArrayList<>();
        while (tR <= dR && tC <= dC) {
            if (tR == dR) {      //  只剩下一行的时候
                for (int i = tC; i <= dC; i++) {
                    ans.add(matrix[tR][i]);
                }
            } else if (tC == dC) {     // 只剩下一列的时候
                for (int i = tR; i <= dR; i++) {
                    ans.add(matrix[i][tC]);
                }
            } else {
                int curC = tC;  // 当前圈的左上角位置所在的列
                int curR = tR;  // 当前圈的左上角位置所在的行
                while (curC != dC) {   // 当前圈的最上边的一行,从左往右
                    ans.add(matrix[tR][curC]);
                    curC++;
                }
                while (curR != dR) {    // 当前圈的最右边的一列,从上到下
                    ans.add(matrix[curR][dC]);
                    curR++;
                } 
                while (curC != tC) {    // 当前圈的最下边的一行,从右到左
                    ans.add(matrix[dR][curC]);
                    curC--;
                }
                while (curR != tR) {    // 当前圈的最左边的一列,从下往上
                    ans.add(matrix[curR][tC]);
                    curR--;
                }
            }
            tR++;
            tC++;
            dR--;
            dC--;
        }
        return ans;
    }

代码参考自:《程序员代码面试指南》----左程云

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/106608393