Skip to content

Latest commit

 

History

History
83 lines (63 loc) · 1.8 KB

79.Word-Search.md

File metadata and controls

83 lines (63 loc) · 1.8 KB

79. Word Search


题目地址

https://leetcode.com/problems/word-search/

题目描述

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

代码

Approach 1: Backtracking

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 (backtrack(row, col, word, 0)) { // match the first letter
          return true;
        }
      }
    }
    return false;
  }

  private 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++) {
      int r = row + rowOffsets[d];
      int c = col + cofOffsets[d];
      ret = backtrack(r, c, word, index + 1);
      if (ret) {
        break;
      }
    }

    this.board[row][col] = word.charAt(index); // 修改回来
    return ret;
  }

}