Sunday, October 20, 2024

Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Solution 

import java.util.ArrayList;
import java.util.List;

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();

if (matrix.length == 0) {
return result;
}

int top = 0; // Starting row
int bottom = matrix.length - 1; // Ending row
int left = 0; // Starting column
int right = matrix[0].length - 1; // Ending column

while (top <= bottom && left <= right) {
// Traverse from left to right across the top row
for (int j = left; j <= right; j++) {
result.add(matrix[top][j]);
}
top++;

// Traverse from top to bottom along the right column
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;

// Traverse from right to left across the bottom row (if any rows left)
if (top <= bottom) {
for (int j = right; j >= left; j--) {
result.add(matrix[bottom][j]);
}
bottom--;
}

// Traverse from bottom to top along the left column (if any columns left)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}

return result;
}
}

No comments:

Post a Comment