LeetCode79. Word Search——回溯

文章目录

一、题目

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

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

Output: true

Example 2:

Input: board = \["A","B","C","E","S","F","C","S","A","D","E","E"], word = "SEE"

Output: true

Example 3:

Input: board = \["A","B","C","E","S","F","C","S","A","D","E","E"], word = "ABCB"

Output: false

Constraints:

m == board.length

n = boardi.length

1 <= m, n <= 6

1 <= word.length <= 15

board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

二、题解

cpp 复制代码
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size(),n = board[0].size();
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                if(f(board,i,j,word,0)) return true;
            }
        }
        return false;
    }
    //从i,j位置出发来到word[k]位置,后续字符是否能走出来
    bool f(vector<vector<char>>& board,int i,int j,string word,int k){
        if(k == word.size()) return true;
        if(i < 0 || i == board.size() || j < 0 || j == board[0].size() || board[i][j] != word[k]) return false;
        char t = board[i][j];
        //为了不重复走
        board[i][j] = '0';
        bool res = f(board,i-1,j,word,k+1) || f(board,i+1,j,word,k+1) || f(board,i,j-1,word,k+1) || f(board,i,j+1,word,k+1);
        board[i][j] = t;
        return res;
    }
};
相关推荐
j7~几秒前
【C语言】《C语言自定义类型(结构体+联合体+枚举类型)》--详解
c语言·开发语言·深度学习·结构体·位段·联合体·枚举类型
乱七八糟的屋子几秒前
AMQP C++ 超详细实战教程(amqp-cpp 开源库从零入门到生产落地)
c++·rabbitmq·任务队列·amqp·流量削峰·c++服务端异步解耦·分布式消息通信
Escalating_xu11 分钟前
C++11 彻底吃透 emplace_back 与 push_back(最全闭环:左右值|深浅拷贝|移动构造|万能引用|完美转发)
开发语言·c++
imuliuliang12 分钟前
关于从栈与队列看算法思维的演化路径7
算法
春生野草18 分钟前
个人笔记--大顶堆和基数排序
java·数据结构·算法
啦啦啦啦啦zzzz24 分钟前
oat++框架应用之do、dao、service
服务器·c++·mysql·oatpp
白狐_79832 分钟前
【408计算机网络|第04章·下|408-CN-04B】网络层(下):路由算法、RIP、OSPF、BGP、IPv6与路由器
计算机网络·算法·智能路由器
皓月斯语44 分钟前
B3865 [GESP202309 二级] 小杨的 X 字矩阵 题解
开发语言·c++·矩阵·题解
donoot2 小时前
PaddleOCR + PyMuPDF 生成【全兼容双层 PDF】完整实操指南
人工智能·算法·pymupdf·paddleocr·双层pdf
paeamecium2 小时前
【PAT甲级真题】- Rational Sum (20)
数据结构·c++·python·算法·pat考试·pat