classSolution{ public List<Integer> spiralOrder(int[][] matrix){ List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int m = matrix.length; int n = matrix[0].length; int i = 0; int j = 0; int direction = 0; int[][] dir = newint[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; boolean[][] visited = newboolean[m][n]; while (res.size() < n * m){ res.add(matrix[i][j]); if (res.size() == n * m) break; visited[i][j] = true; int ni = i + dir[direction][0]; int nj = j + dir[direction][1]; while( ni >= m || nj >= n || ni < 0 || nj < 0 || visited[ni][nj]){ direction ++; if (direction > 3) direction = 0; ni = i + dir[direction][0]; nj = j + dir[direction][1]; } i = ni; j = nj; } return res; } }