Sunday, April 30, 2017

54. Spiral Matrix

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].



Solution:

This is a straightforward implementation. While the matrix still leaves some elements to be checked, we do:

1. Go right if possible. Update boundary when finished.

2. Go down if possible. Update boundary when finished.

3. Go left if possible. Update boundary when finished.

4. Go up if possible. Update boundary when finished.



Code:


public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }
        if (matrix[0] == null || matrix[0].length == 0) {
            return result;
        }
        
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        
        while (result.size() != matrix.length * matrix[0].length) {
            // go left
            if(left > right || bottom < top) {
                break;
            }
            for (int j = left; j <= right; j++) {
                result.add(matrix[top][j]);
            }
            top++;
            
            if(left > right || bottom < top) {
                break;
            }
            // go down
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;
            
            // go right
            if(left > right || bottom < top) {
                break;
            }
            for (int j = right; j >= left; j--) {
                result.add(matrix[bottom][j]);
            }
            bottom--;
            
            // go up
            if(left > right || bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                result.add(matrix[i][left]);
            }
            left++;
        }
        
        return result;
    }
}