LeetCode:60.单词搜索

目录

1.单词搜索


1.单词搜索

cpp 复制代码
class Solution {
    bool check[7][7];
    int m, n;
public:
    bool exist(vector<vector<char>>& board, string word) 
    {
        m = board.size(), n = board[0].size();
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                if(board[i][j] == word[0])
                {
                    check[i][j] = true;
                    if(dfs(board, i, j, word, 1) == true) return true;
                    check[i][j] = false;
                }
        return false;
    }

    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};

    bool dfs(vector<vector<char>>& board, int i, int j, string word, int pos)
    {
        
        if(pos == word.size()) return true;
        for(int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && board[x][y] == word[pos])
            {
                check[x][y] = true;
                if(dfs(board, x, y, word, pos + 1) == true) return true;
                check[x][y] = false;
            }
        }
        return false;
    }
};
相关推荐
yyy(十一月限定版)44 分钟前
寒假集训4——二分排序
算法
星火开发设计44 分钟前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉1 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子1 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
培风图南以星河揽胜1 小时前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着2591 小时前
力扣hot100 - 234、回文链表
算法·leetcode·链表
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-多维动态规划篇(不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离)
数据结构·学习·算法