Untitled

 avatar
user_6837451
java
a year ago
1.3 kB
3
Indexable
Never

class Solution {
  public List<Integer> spiralOrder(int[][] matrix) {
    final var result = new ArrayList<Integer>();
    spiralOrder(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, 't', result);
    return result;
  }

  private void spiralOrder(
      int[][] matrix,
      int fromRow,
      int fromCol,
      int toRow,
      int toCol,
      char edge,
      List<Integer> result) {
    if (fromRow > toRow || fromCol > toCol) {
      return;
    }

    if (edge == 't') {
      for (int i = fromCol; i <= toCol; i++) {
        result.add(matrix[fromRow][i]);
      }
      spiralOrder(matrix, fromRow + 1, fromCol, toRow, toCol, 'r', result);
      return;
    }

    if (edge == 'r') {
      for (int i = fromRow; i <= toRow; i++) {
        result.add(matrix[i][toCol]);
      }
      spiralOrder(matrix, fromRow, fromCol, toRow, toCol - 1, 'b', result);
      return;
    }

    if (edge == 'b') {
      for (int i = toCol; i >= fromCol; i--) {
        result.add(matrix[toRow][i]);
      }
      spiralOrder(matrix, fromRow, fromCol, toRow - 1, toCol, 'l', result);
      return;
    }

    for (int i = toRow; i >= fromRow; i--) {
      result.add(matrix[i][fromCol]);
    }
    spiralOrder(matrix, fromRow, fromCol + 1, toRow, toCol, 't', result);
  }
}