79. 单词搜索

231 阅读1分钟
  1. 单词搜索

leetcode-cn.com/problems/wo… 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false。

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

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"


class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        // board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
        int h = board.size(), w = board[0].size();
        
        vector<vector<int>> visited(h, vector<int>(w));
        // 遍历每个单词 
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                if (isEqual(board, visited, word, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    bool isEqual(vector<vector<char>>& board, vector<vector<int>>& visited, string& s, int i, int j, int k) {
        // 判断匹配单词字母
        if (board[i][j] != s[k]) {
            return false;
        }
        if (k == s.length() - 1) {
            return true;
        }

        visited[i][j] = true;
        vector<pair<int,int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        bool result = false;
        // 当前位置字母匹配后,进行下一个字母位置的匹配k+1
        // 宫格遍历 1.未访问过 2.回溯获取下一个位置匹配结果 3.回溯完恢复本次访问状态
        for (const auto& dir: directions) {
            int newx = i + dir.first, newy = j + dir.second;
            if (newx >= 0 && newx < board.size() && newy >= 0 && newy < board[0].size()) {                
                if (!visited[newx][newy]) {
                    bool flag = isEqual(board, visited, s, newx, newy, k + 1);
                    if (flag) {
                        result = true;
                        break;
                    }
                }
            }
        }
        visited[i][j] = false;
        return result;
    }
};