Simple, recursive solution [JAVA]


  • 0
    P
    class Solution {
        static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
    
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();
            if (matrix == null || matrix.length == 0) return result;
            
            addEdge(0, matrix, result, 0, 0);
            return result;
        }   
        
        private void addEdge(int iteration, int[][] matrix, List<Integer> result, int r, int c) {
            int[] currentDirection = DIRECTIONS[iteration % 4];
            /*
                0 -> n - 0
                1 -> m - 1
                2 -> n - 1
                3 -> m - 2
                4 -> n - 2
                5 -> m - 3
                6 -> n - 3
            */
            
            int iterationCount = iteration % 2 == 0 ? matrix[0].length - (iteration / 2) : matrix.length - ((iteration + 1) / 2);
            if (iterationCount <= 0) return;
            
            int x = 0;
            int y = 0;
            for(int i = 0; i < iterationCount; i += 1) {
                x = (i * currentDirection[0]) + r;
                y = (i * currentDirection[1]) + c;
                result.add(matrix[x][y]);
            }
            
            int[] nextDirection = DIRECTIONS[(iteration + 1) % 4];
            addEdge(iteration + 1, matrix, result, x + nextDirection[0], y + nextDirection[1]);
        }
    }
    

    Please leave your feedback :)


Log in to reply
 

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