My easy to understand Java solution


  • 0
    Z

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

        List<Integer> result = new ArrayList<Integer>();
        if (matrix.length == 0) {
            return result;
        }
        int direction = 1; // values can be between 1 to 4
        int i = 0;
        int j = matrix.length-1;
        int l = 0;
        int h = matrix[0].length-1;
        
        
        //algorithm is that fundamentally 4 directions horizontal right, vertical down, horizontal left, vertical up
        while ((i<=j) && (l<=h)) {
            if (direction == 1) {
                int start1 = l;
                while (start1 <= h) {
                    result.add(matrix[i][start1]);
                    start1++;
                }
                //switch direction
                i++;
                direction = 2;
            }
            else if (direction == 2) {
                int start2 = i;
                while (start2 <= j) {
                    result.add(matrix[start2][h]);
                    start2++;
                }
                h--;
                direction = 3;
            }
            else if (direction == 3) {
                int start3 = h;
                while (start3 >= l) {
                    result.add(matrix[j][start3]);
                    start3--;
                }
                j--;
                direction = 4;
            }
            else {
                int start4 = j;
                while (start4 >= i) {
                    result.add(matrix[start4][l]);
                    start4--;
                }
                l++;
                direction = 1;
            }
        }
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.