79. Word Search

JJ·2021년 1월 19일
0

Algorithms

목록 보기
71/114

class Solution {
  private char[][] board;
  private int ROWS;
  private int COLS;

  public boolean exist(char[][] board, String word) {
    this.board = board;
    this.ROWS = board.length;
    this.COLS = board[0].length;

    for (int row = 0; row < this.ROWS; row++)
      for (int col = 0; col < this.COLS; col++)
        if (this.backtrack(row, col, word, 0))
          return true;
    return false;
  }

  protected boolean backtrack(int row, int col, String word, int index) {
    if (index >= word.length())
      return true;

    if (row < 0 || row == this.ROWS || col < 0 || col == this.COLS
        || this.board[row][col] != word.charAt(index))
      return false;

    boolean ret = false;
    this.board[row][col] = '#';

    int[] rowOffsets = {0, 1, 0, -1};
    int[] colOffsets = {1, 0, -1, 0};
    for (int d = 0; d < 4; d++) {
      ret = this.backtrack(row + rowOffsets[d], col + colOffsets[d], word, index + 1);
      if (ret)
        break;
    }

    this.board[row][col] = word.charAt(index);
    return ret;
  }
}

Runtime: 6 ms, faster than 55.85% of Java online submissions for Word Search.
Memory Usage: 40.2 MB, less than 85.97% of Java online submissions for Word Search.

DFS...backtrack....
용어는 알지만 푸는 방법을 모르겠네욥^^

0개의 댓글

관련 채용 정보