找規(guī)律-螺旋矩陣

螺旋矩陣

https://leetcode.cn/problems/spiral-matrix/description/

題目分析

跟螺旋矩陣類似,順時針先打印最外圈元素,然后頂點索引遞進(jìn),打印內(nèi)圈元素,在打印一圈元素時,分別沿著4個方向打印,然后繼續(xù)打印內(nèi)圈元素;

截屏2024-07-15 上午8.01.18.png

編程實現(xiàn)

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList();
        if(matrix == null || matrix.length <= 0){
            return list;
        }
        int left = 0;
        int right = matrix[0].length-1;
        int bottom = matrix.length - 1;
        int top = 0;
        while(left <= right && top <= bottom){
            //打印行
            for(int i = left;i <= right;i++){
                list.add(matrix[top][i]);
            }
            //打印右側(cè)
            for(int i = top+1;i <= bottom;i++){
                list.add(matrix[i][right]);
            }
            //打印最底行,top!= bottom ,只有一行情況下 6 7 9
            if(top != bottom){
                for(int i = right -1;i >= left;i--){
                    list.add(matrix[bottom][i]);
                }
            }
            
            /**
             打印最左側(cè) left!=right 條件,只有一列情況下
             6
             7
             9
             */
            if(left != right){
                for(int i = bottom -1;i > top;i--){
                    list.add(matrix[i][left]);
                }
            }
            left++;
            right--;
            bottom--;
            top++;
        }
        return list;
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容