Simple java solution using direction arrays


  • 1
    K
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            int [] dr = new int[]{0,1,0,-1};
            int [] dc = new int[]{1,0,-1,0};
            
            List<Integer> spiral = new ArrayList<Integer>();
            if(matrix.length ==0) return spiral;
            
            int R = matrix.length, C = matrix[0].length;
            int dir = 0, newR = 0, newC = 0, count = 0;
            boolean [][] visited = new boolean[R][C];
            
            while(true) {
                if(count == R*C) break;
                spiral.add(matrix[newR][newC]);
                visited[newR][newC] = true;
                
                if(newR + dr[dir] < 0 
                    || newR + dr[dir] >= R 
                    || newC + dc[dir] < 0 
                    || newC + dc[dir] >= C
                    || visited[newR + dr[dir]][newC + dc[dir]]
                    ) {
                    dir = (dir+1)%4;
                }
                
                newR = newR + dr[dir];
                newC = newC + dc[dir];
                
                count += 1;
            }
            return spiral;
        }
    }

Log in to reply
 

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