leetcode54- Spiral Matrix- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode54- Spiral Matrix- medium相关的知识,希望对你有一定的参考价值。

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

 

每一while循环内做一次圈打印。一圈打印做4个for循环,每个for循环做一个方向。做好后更新一下某个方向的边界。

细节:中间需要检查一下是否会因为奇数窄形状导致的同条回荡。

 

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }
        
        int m = matrix.length, n = matrix[0].length;
        int top = 0, bottom = m - 1, left = 0, right = n - 1;
        
        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;
            
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;
            
            // 为了避免那种窄的,单数行的最后左右回荡两次
            if (top > bottom || left > right) {
                break;
            }
            
            for (int i = right; i >= left; i--) {
                result.add(matrix[bottom][i]);
            }
            bottom--;
            
            for (int i = bottom; i >= top; i--) {
                result.add(matrix[i][left]);
            }
            left++;
        }
        
        return result;
    }
}

 


以上是关于leetcode54- Spiral Matrix- medium的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode54 Spiral Matrix

LeetCode 54. Spiral Matrix

[LeetCode]Spiral Matrix 54

[LeetCode]54. Spiral Matrix

[leetcode][54] Spiral Matrix

LeetCode54 Spiral Matrix