矩阵中的路径

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

思路:

遍历二维字符网格,以当前位置(i,j)为起点,判断board[i][j]与word[index](index从i,j起点开始为0,后面一次加1)是否相等,如果不等,则查看下个位置。如果相等以(i,j)为中心向四周四个位置扩散,(i+1,j)、(i-1,j)、(i,j+1)、(i,j-1)与index+1位置的word字符是否相等,如果相等,则继续进行下一轮比较。递归。

代码:

class Solution {
private:
    vector<vector<bool>> visited;
public:
    bool hasWord(vector<vector<char>>& board,int row,int col , string& word, int index) {
        //如果当前字母和word相应位置的字母不等,则自己返回false
        if(board[row][col] != word[index]) {
            return false;
        }
        else if(index == word.length()-1) {
            //如果当前字符和word相应位置的字母相等,并且当前是word的最后一个字符,则返回true,找到一条路径
            return true;
        }
        visited[row][col] = true;
        bool result = false;
        vector<pair<int,int>> directions{{0,1},{0,-1},{1,0},{-1,0}};
        for(const auto& direction: directions) {
            int newRow = row + direction.first;
            int newCol = col + direction.second;
            if(newRow >= 0 && newRow < board.size() && newCol >= 0 && newCol < board[0].size()) {
                if(!visited[newRow][newCol]) {
                    bool f = hasWord(board,newRow,newCol,word,index+1);
                    //周围四个位置有一个可以找到,则返回true
                    if(f) {
                        result = true;
                        break;
                    }
                }
            }
        }
        visited[row][col] = false;
        return result;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int rows = board.size();
        if (rows == 0) {
            return false;
        }
        int cols = board[0].size();
        visited.resize(rows,vector<bool>(cols));
        //遍历二维字母网格
        for(int i = 0;i < rows;i++) {
            for(int j = 0;j < cols;j++) {
                bool result = hasWord(board,i,j,word,0);
                //如果存在当前位置为起点的路径,则返回true
                if(result) {
                    return true;
                }
            }
        }
        return false;
    }
};