首页 > 代码库 > (每日算法)LeetCode --- Word Search(矩阵中查找单词)

(每日算法)LeetCode --- 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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

//如何构造辅助函数的参数?
//逐个字母匹配的时候,如何传递下一个要匹配的字母?---通过索引参数的形式
//走过的路要标记,不管可行不可行,都要重新标记?
//边界条件的考虑?
class Solution {
public:
    bool exist(vector<vector<char>> &board, string word) {
        const int m = board.size();
        const int n = board[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));//将访问标记数组置空
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                if(dfs(board, word, 0, i, j, visited))//单词可在任意位置开始匹配
                    return true;                      //只要有一个位置完全匹配即匹配
        return false;
    }
    static bool dfs(vector<vector<char>> &board, string word, int index,
                    int x, int y, vector<vector<bool>>& visited)//辅助函数,自定义参数
    {
        if(index == word.size())    //单词大小和索引相等即匹配
                                    //当单词为空的时候是满足的
                                    //下一个要查找的索引和单词大小相等说明,
                                    //word的0 - index的位置的字母已经匹配
            return true;
        if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) //不可越界
            return false;
        if(visited[x][y]) //如果之前访问过,那么直接返回false
            return false;
        if(board[x][y] != word[index]) //不相等,这条路走不通,剪枝
            return false;
        visited[x][y] = true; //先标记为走过,因为下一次会走向四个方向
        bool ret = dfs(board, word, index + 1, x, y + 1, visited) ||
                dfs(board, word, index + 1, x, y - 1, visited)    ||
                dfs(board, word, index + 1, x - 1, y, visited)     || 
                dfs(board, word, index + 1, x + 1, y, visited); 
        visited[x][y] = false;  //走过之后,不过不匹配,要还原为没有走过
        return ret;
    }
};



(每日算法)LeetCode --- Word Search(矩阵中查找单词)