Example: Spiral - rFronteddu/general_wiki GitHub Wiki

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

Solution

  • Prepare four directions,
  • Each time you reach the limit of the current direction, reduce it by on
  • Continue until you do all the mxn cells.
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new LinkedList<>();
        
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        int count = 0;
        int c = 0;
        int r = 0;
        
        int downLim = rows - 1;
        int rightLim = cols - 1;
        int leftLim = 0;
        int upLim = 1;
        
        boolean up = false;
        boolean down = false;
        boolean left = false;
        boolean right = true;
        
        
        
        while (count < rows * cols) {    
            result.add (matrix[r][c]);
            count++;
            
            
            if (right) {
                if (c != rightLim) {
                    // keep going right
                    c++;
                } else {
                    // time to go down
                    right = false;
                    down = true;
                    r++;
                    // next time you go right you end a column early
                    rightLim--; 
                }
            } else if (down) {
                if (r != downLim) {
                    // keep going down
                    r++;
                } else {
                    // go left
                    down = false;
                    left = true;
                    c--;
                    // next time you go down you end a row early
                    downLim--;
                }
            } else if (left) {
                if (c != leftLim) {
                    // keep going left
                    c--;
                } else {
                    // go up
                    left = false;
                    up = true;
                    r--;
                    leftLim++;
                }
            } else if (up) {
                if (r != upLim) {
                    // keep going up
                    r--;
                } else {
                    // go right
                    up = false;
                    right = true;
                    c++;
                    upLim++;
                }
            }
        }    
        return result;
    }
}
⚠️ **GitHub.com Fallback** ⚠️