LeetCode 79. Word Search C++

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.

Example:

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.

Approach

  1. 这道题也是比较经典的递归回溯题,从一个矩阵中是否能拼凑成word,然后每个字母只能用一次,所以很明显需要记录它的轨迹,我们开辟一个轨迹vis,然后我们递归查找它的四个方向,上下左右,走过的地方要标记,然后假如有一个方向找到了,那么直接返回,如果所有方向都查找不到,将此时的标记的抹去,因为不确定是否会在其他轨迹用到这个字母。16ms
  2. 发现多次调用size()方法,会减低速度,所以让其变成全局变量了。

Code

class Solution {
public:
    int N, M, wordlen;
    bool exist(vector<vector<char>>& board, string word) {
        if (board.size() == 0)return false;
        vector<vector<int>>dir{ {0,0,1,-1},{1,-1,0,0} };
        N = board.size(), M = board[0].size(), wordlen = word.size();
        vector<vector<int>>vis(N, vector<int>(M, false));
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (board[i][j] == word[0]){
                    vis[i][j] = true;
                    if (FindWordInBoard(dir, board, vis, string(1, board[i][j]), word, i, j, 1)) {
                        return true;
                    }
                    else {
                        vis[i][j] = false;
                    }
                }
            }
        }
        return false;
    }
    bool FindWordInBoard(vector<vector<int>>&dir,vector<vector<char>>& board,vector<vector<int>>&vis,string cur,string &word,int x,int y,int pos) {
        if (pos == wordlen) {
            return true;
        }
        for (int i = 0; i < 4; i++) {
            int newx = x + dir[0][i];
            int newy = y + dir[1][i];
            if (newx<0 || newy<0 || newx>N - 1 || newy>M - 1)continue;
            if (!vis[newx][newy]&&board[newx][newy] == word[pos]) {
                vis[newx][newy] = true;
                if (FindWordInBoard(dir, board, vis, cur, word, newx, newy, pos + 1)) {
                    return true;
                }
                else {
                    vis[newx][newy] = false;
                }
            }
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值