79. 单词搜索-dfs地图搜索-注意从第二个字符开始dfs

问题

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

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

分析

dfs,注意会有多个起点,每个起点memset(st, 0, sizeof st);后要将起点设置为已访问。不要将continue写成return。

代码

class Solution {
public:
    vector<vector<char> > g;
    string word;
    int n;
    int m;
    bool res = false;
    int nx[4] = {1, 0, -1, 0};
    int ny[4] = {0, -1, 0, 1};
    int st[7][7];
    void dfs(int x, int y, int i_word) {
        if (g[x][y] != word[i_word]) {return ;} // 判断当前字符
        if (i_word == word.size()-1) {res = true; return ;}
        for (int i = 0; i < 4; i++) { // 处理下一个
            int a = x+nx[i]; int b = y+ny[i];
            if (a >= n || b >= m || a < 0 || b < 0) {continue ;} // continue不要写成return
            if (st[a][b] == 1) {continue ;}
            st[a][b] = 1;
            dfs(a, b, i_word+1);
            st[a][b] = 0;
        }
    }
    bool exist(vector<vector<char>>& board, string word) {
        this->g = board;
        this->word = word;
        n = board.size();
        m = board[0].size();
        int start_x = -1, start_y = -1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (g[i][j] == word[0]) {
                    memset(st, 0, sizeof st);
                    start_x = i; start_y = j;
                    st[start_x][start_y] = 1;
                    dfs(start_x, start_y, 0); // 可能有多个起点
                }
            }
        }
        return res;

    }
};

new

class Solution {
private:
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, -1, 0, 1};
    string word;
    int res = 0;
    int n = 0, m = 0;
    int st[8][8];
    vector<vector<char>> board;
    void dfs(int x, int y, int cur) {
        if (cur == word.size()) {res = 1; return ;}
        for (int i = 0; i < 4; i++) {
            int a = x + dx[i];
            int b = y + dy[i];
            if (a < 0 || a >= n || b < 0 || b >= m) {continue;}
            if (st[a][b]) {continue;}
            if (board[a][b] != word[cur]) {continue;}
            st[a][b] = 1;
            dfs(a, b, cur+1);
            st[a][b] = 0;
        }
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        this->n = board.size(); this->m = board[0].size();
        this->board = board; this->word = word;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == word[0]) {
                    memset(st, 0, sizeof st);
                    st[i][j] = 1;
                    dfs(i, j, 1);
                }
            }
        }
        return res;
    }
};
posted @ 2025-06-04 18:45  saulstavo  阅读(16)  评论(0)    收藏  举报