DEV Community

Debesh P.
Debesh P.

Posted on

54. Spiral Matrix | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/spiral-matrix/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/spiral-matrix/solutions/7466931/most-optimal-solution-beats-500-matrix-y-nez1


leetcode 54


Solution

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> res = new ArrayList<>();

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }

        int rows = matrix.length;
        int cols = matrix[0].length;
        int left = 0, right = cols - 1;
        int top = 0, bottom = rows - 1;

        // right --> bottom --> left --> top

        while (top <= bottom && left <= right) {

            // right
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            top++;

            // --> bottom
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            right--;

            // --> left
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    res.add(matrix[bottom][i]);
                }
                bottom--;
            }

            // --> top
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;
            }
        }

        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)