leetcode題目54. 螺旋矩陣

題目描述

給你一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。

示例

輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]

代碼

    private static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length <= 0) {
            return result;
        }
        int top = 0;
        int right = matrix[0].length - 1; //
        int left = 0;
        int bottom = matrix.length - 1; // 二維數(shù)組的lengh是行數(shù)
        int remainElementCount = matrix.length * matrix[0].length; // 二維數(shù)組中元素數(shù)量

        while (remainElementCount > 0) {
            // 從左上到右上
            for (int i = left; i <= right && remainElementCount > 0; i++ ) {
                result.add(matrix[top][i]);
                remainElementCount --;
            }
            top ++;

            // 從右上往右下
            for (int j = top; j <= bottom && remainElementCount > 0; j++ ) {
                result.add(matrix[j][right]);
                remainElementCount --;
            }
            right --;

            // 從右下到左下
            for (int k = right; k >= left && remainElementCount > 0; k -- ) {
                result.add(matrix[bottom][k]);
                remainElementCount --;
            }
            bottom --;

            // 從左下到左上
            for (int e = bottom; e >= top && remainElementCount > 0; e -- ) {
                result.add(matrix[e][left]);
                remainElementCount --;
            }
            left ++;
        }
        return result;
    }


?著作權(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)容