Exercise letter:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example, Given the
Try this.
static int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
static boolean movable(int r, int c, int height, int width, boolean[][] visited) {
if (r < 0 || r >= height || c < 0 || c >= width)
return false;
return !visited[r][c];
}
public List spiralOrder(int[][] matrix) {
List result = new ArrayList<>();
int height = matrix.length;
if (height == 0) return result;
int width = matrix[0].length;
if (width == 0) return result;
boolean[][] visited = new boolean[height][width];
int direction = 0;
int r = 0, c = 0;
for (int i = 0; i < width * height; ++i) {
result.add(matrix[r][c]);
visited[r][c] = true;
int[] directions = DIRECTIONS[direction % DIRECTIONS.length];
if (!movable(r + directions[0], c + directions[1], height, width, visited))
directions = DIRECTIONS[++direction % DIRECTIONS.length];
r += directions[0];
c += directions[1];
}
return result;
}