刷题之单词搜索(leetcode)

在这里插入图片描述

很容易就想到回溯

class Solution {
private:
    int istrue = false;
    int dir[4][2] = { -1,0,0,-1,0,1,1,0 };
    void backtracking(vector<vector<char>>& board, string word, vector<vector<bool>>& visited, int x, int y, int index)
    {
        if (index == word.size())//当找全word的字母,则标记
        {
            istrue = true;
            return;
        }
        
        for (int i = 0; i < 4; i++)
        {
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx >= board.size() || nexty >= board[0].size() || nextx < 0 || nexty < 0)
                continue;
            if (visited[nextx][nexty] == false && board[nextx][nexty] == word[index])
            {
                visited[nextx][nexty] = true;
                backtracking(board, word, visited, nextx, nexty, index + 1);
                visited[nextx][nexty] = false;//回溯
            }
        }
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        vector<vector<bool>>visited(board.size(), vector<bool>(board[0].size(), false));
        for (int i = 0; i < board.size(); i++)
        {
            for (int j = 0; j < board[0].size(); j++)
            {
                //遍历所有字母,找到word中第一个字母,再进行深度优先搜索找word的其他字母
                if (board[i][j] == word[0])
                {
                    visited[i][j] = true;
                    backtracking(board, word, visited, i, j, 1);
                    visited[i][j] = false;//回溯
                    //一旦找到,直接返回
                    if(istrue)
                        return true;
                }
            }
        }
        return istrue;
    }
};

相关推荐

  1. leetcodeMySQL】

    2024-05-25 22:06:59       52 阅读
  2. leetcode算法】

    2024-05-25 22:06:59       52 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-25 22:06:59       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-25 22:06:59       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-25 22:06:59       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-25 22:06:59       20 阅读

热门阅读

  1. 在Ubuntu20.04.6上编译Qt5.15.2源码并安装

    2024-05-25 22:06:59       12 阅读
  2. ROS+UBUNTU开发常用指令

    2024-05-25 22:06:59       11 阅读
  3. Ubuntu 安装libpng12的方法

    2024-05-25 22:06:59       10 阅读
  4. 前端中css穿透样式:deep的用法

    2024-05-25 22:06:59       11 阅读
  5. 面向对象的三大特征和五大基本原则

    2024-05-25 22:06:59       10 阅读
  6. android 水平居中对齐并举例

    2024-05-25 22:06:59       12 阅读
  7. 过滤器 -- Filter

    2024-05-25 22:06:59       8 阅读
  8. 【sass数字运算简介以及使用方法】

    2024-05-25 22:06:59       12 阅读
  9. 一些Spring Boot直接的解释

    2024-05-25 22:06:59       10 阅读
  10. 判断当前系统是linux、windows还是MacOS (python)

    2024-05-25 22:06:59       13 阅读
  11. C++基础:构建者设计模式

    2024-05-25 22:06:59       11 阅读
  12. 单元测试:保证重构不出错的有效手段

    2024-05-25 22:06:59       10 阅读