|
| 1 | +class Solution { |
| 2 | + // right, down, left, up |
| 3 | + int[] dx = {0, 1, 0, -1}; |
| 4 | + int[] dy = {1, 0, -1, 0}; |
| 5 | + boolean[][] visit; |
| 6 | + |
| 7 | + int m; |
| 8 | + int n; |
| 9 | + public List<Integer> spiralOrder(int[][] matrix) { |
| 10 | + m = matrix.length; |
| 11 | + n = matrix[0].length; |
| 12 | + visit = new boolean[m][n]; |
| 13 | + return bfs(matrix); |
| 14 | + } |
| 15 | + |
| 16 | + public boolean outOfRange(int x, int y){ |
| 17 | + return ((x < 0 || x >= m) || (y < 0 || y >= n)); |
| 18 | + } |
| 19 | + |
| 20 | + public List<Integer> bfs(int[][] matrix) { |
| 21 | + List<Integer> spiral = new ArrayList<>(); |
| 22 | + |
| 23 | + Queue<Point> q = new ArrayDeque<>(); |
| 24 | + |
| 25 | + int startX = 0; |
| 26 | + int startY = 0; |
| 27 | + int startDir = 0; |
| 28 | + |
| 29 | + q.add(new Point(startX, startY, startDir)); |
| 30 | + visit[startX][startY] = true; |
| 31 | + |
| 32 | + while (!q.isEmpty()){ |
| 33 | + Point cur = q.poll(); |
| 34 | + spiral.add(matrix[cur.x][cur.y]); |
| 35 | + |
| 36 | + int nextX = cur.x + dx[cur.dir]; |
| 37 | + int nextY = cur.y + dy[cur.dir]; |
| 38 | + int nextDir = cur.dir; |
| 39 | + |
| 40 | + if (outOfRange(nextX, nextY) || visit[nextX][nextY]) { |
| 41 | + nextDir = (nextDir + 1) % 4; |
| 42 | + } |
| 43 | + |
| 44 | + nextX = cur.x + dx[nextDir]; |
| 45 | + nextY = cur.y + dy[nextDir]; |
| 46 | + |
| 47 | + if (!outOfRange(nextX, nextY) && !visit[nextX][nextY]){ |
| 48 | + q.add(new Point(nextX, nextY, nextDir)); |
| 49 | + visit[nextX][nextY] = true; |
| 50 | + } |
| 51 | + } |
| 52 | + return spiral; |
| 53 | + } |
| 54 | + |
| 55 | + class Point{ |
| 56 | + int x; |
| 57 | + int y; |
| 58 | + int dir; |
| 59 | + public Point(int x, int y, int dir){ |
| 60 | + this.x = x; |
| 61 | + this.y = y; |
| 62 | + this.dir = dir; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
| 67 | + |
| 68 | + |
0 commit comments