๐ŸŒ— ๅ‰‘ๆŒ‡ Offer 29. ้กบๆ—ถ้’ˆๆ‰“ๅฐ็Ÿฉ้˜ต

ๅžไฝ›็ซฅๅญ2022ๅนด10ๆœˆ10ๆ—ฅ
  • algorithm
  • Array
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ— ๅ‰‘ๆŒ‡ Offer 29. ้กบๆ—ถ้’ˆๆ‰“ๅฐ็Ÿฉ้˜ต

้šพๅบฆ: ๐ŸŒ—

้—ฎ้ข˜ๆ่ฟฐ

img_31.png


่งฃๆณ•

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        // ๆ€่ทฏ๏ผš
        // ๅ››ไธชๆ–นๅ‘้ๅŽ†
        int row = matrix.length;
        if(row == 0) {
            return new int[0];
        }
        int col = matrix[0].length;
        if(col == 0) {
            return new int[0];
        }
        int top = 0;
        int bottom = row - 1;
        int left = 0;
        int right = col - 1;

        int len = row * col;
        int[] res = new int[len];
        int index = 0;
        while(top <= bottom && left <= right) {
            // ๅทฆ --> ๅณ
            for(int j = left; j <= right; j ++) {
                res[index] = matrix[top][j];
                index ++;
            }
            top ++;
            // System.out.println(index + "  " + top + "  " + bottom + "  " + left + "  " + right);
            if(index == len) {
                return res;
            }
            // ไธŠ --> ไธ‹
            for(int i = top; i <= bottom; i ++) {
                res[index] = matrix[i][right];
                index ++;
            }
            right --;
            // System.out.println(index + "  " + top + "  " + bottom + "  " + left + "  " + right);
            if(index == len) {
                return res;
            }
            // ๅณ --> ๅทฆ
            for(int j = right; j >= left; j --) {
                res[index] = matrix[bottom][j];
                index ++;
            }
            bottom --;
            // System.out.println(index + "  " + top + "  " + bottom + "  " + left + "  " + right);
            if(index == len) {
                return res;
            }
            // ไธ‹ --> ไธŠ
            for(int i = bottom; i >= top; i --) {
                res[index] = matrix[i][left];
                index ++;
            }
            left ++;
            // System.out.println(index + "  " + top + "  " + bottom + "  " + left + "  " + right);
            if(index == len) {
                return res;
            }
        }
        return res;
    }
}

่พ“ๅ‡บ

img_30.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/10/10 ไธ‹ๅˆ8:43:48
่ดก็Œฎ่€…: liuxianzhishou