GH1995 / leetcode-test-and-run

方便 leetcode 刷题的小工具
GNU General Public License v2.0
0 stars 0 forks source link

79. Word Search 词语搜索 #41

Open GH1995 opened 5 years ago

GH1995 commented 5 years ago

79. Word Search

Difficulty: Medium

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.

Solution

Language: C++

class Solution {
 public:
  bool exist(vector<vector<char>> &board, string word) {
    if (board.empty() || word.empty()) return 0;
​
    for (int x = 0; x < board.size(); ++x)
      for (int y = 0; y < board[0].size(); ++y)
        if (exist(x, y, 0, word, board)) return true;
​
    return false;
  }
​
  bool exist(int x, int y, int pos, string &word, vector<vector<char>> &board) {
    if (pos == word.size()) return true;
    if (x < 0 || x == board.size() || y < 0 || y == board.front().size())
      return false;
​
    if (board[x][y] != word[pos]) return false;
​
    auto cur = board[x][y];
    board[x][y] = '*';
    auto search = exist(x + 1, y, pos + 1, word, board) ||
                  exist(x - 1, y, pos + 1, word, board) ||
                  exist(x, y + 1, pos + 1, word, board) ||
                  exist(x, y - 1, pos + 1, word, board);
    board[x][y] = cur;
​
    return search;
  }
};
GH1995 commented 5 years ago
  1. x = board.size() and y = board.front().size()
  2. 先判断true or false
  3. 保存状态
  4. 拓展四个方向
  5. 恢复状态
for x: 0 -> m
    for y: 0 -> n
        if exist(x, y)
            return true

return false

原二维数组就像是一个迷宫,可以上下左右四个方向行走,我们以二维数组中每一个数都作为起点和给定字符串做匹配,我们还需要一个和原数组等大小的visited数组,是bool型的,用来记录当前位置是否已经被访问过,因为题目要求一个cell只能被访问一次。如果二维数组board的当前字符和目标字符串word对应的字符相等,则对其上下左右四个邻字符分别调用DFS的递归函数,只要有一个返回true,那么就表示可以找到对应的字符串,否则就不能找到

我们还可以不用visited数组,直接对board数组进行修改,将其遍历过的位置改为井号,记得递归调用完后需要恢复之前的状态