美文网首页
LeetCodeDay54 —— 单词搜索★★

LeetCodeDay54 —— 单词搜索★★

作者: GoMomi | 来源:发表于2018-06-09 13:28 被阅读0次

79. 单词搜索 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.
示例
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.
思路
  1. 从每个字母开始,依次向上、下、左、右四个方向延续,如果满足则继续,不满足就返回。很典型的回溯算法。
  2. 注意每次遍历的时候需要标记当前节点为已访问,否则会出现圈,造成死循环。
class Solution {
 public:
  bool exist(vector<vector<char>>& board, string word) {
    if (board.empty() || board[0].empty()) return false;
    vector<vector<bool>> tag;
    vector<bool> tmp(board[0].size(), false);
    for (int i = 0; i < board.size(); ++i) {
      tag.push_back(tmp);
    }
    for (int i = 0; i < board.size(); ++i) {
      for (int j = 0; j < board[0].size(); ++j) {
        bool isFind = _exist(0, i, j, word, board, tag);
        if (isFind) return true;
      }
    }
    return false;
  }
  bool _exist(int k, int row, int col, string& word,
              vector<vector<char>>& board, vector<vector<bool>>& tag) {
    bool isFind = false;
    if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size()) {
      return isFind;
    }
    if (!tag[row][col] && board[row][col] == word[k]) {
      if (k == word.size() - 1) return true;
      tag[row][col] = true;
      isFind = _exist(k + 1, row - 1, col, word, board, tag) ||
               _exist(k + 1, row + 1, col, word, board, tag) ||
               _exist(k + 1, row, col - 1, word, board, tag) ||
               _exist(k + 1, row, col + 1, word, board, tag);
      tag[row][col] = false;
    }
    return isFind;
  }
};

相关文章

  • LeetCodeDay54 —— 单词搜索★★

    79. 单词搜索 Word Search 描述 Given a 2D board and a word, find...

  • 单词搜索

    给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中...

  • 单词搜索

  • 单词搜索

    题目:给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成...

  • 单词搜索

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/word...

  • leetcode212 单词搜索II

    题目 单词搜索II 暴力解法 暴力解法就是用leetcode79 单词搜索这题的搜索一个单词的dfs方法,挨个搜索...

  • python实现leetcode之79. 单词搜索

    解题思路 不断搜索单词的后缀或者单词搜索完,返回True或者无路可走,周围都被搜索过,返回False 79. 单词...

  • LeetCode-79-单词搜索(Word Search)

    LeetCode-79-单词搜索(Word Search) 79. 单词搜索[https://leetcode-c...

  • LeetCode 单词搜索

    题目描述: 解题思路:这里考虑到使用字符串,并且设计到字符的搜索,想到采用前缀树来进行存储,并根据前缀树进行搜索 ...

  • 【leetcode】单词搜索

    【leetcode】单词搜索 题目: 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺...

网友评论

      本文标题:LeetCodeDay54 —— 单词搜索★★

      本文链接:https://www.haomeiwen.com/subject/bfyteftx.html