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;
    }
};
相关推荐
语戚10 小时前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
君顾110 小时前
本地托管机构管理源码实战:需求拆解、数据建模与多端部署
java·开发语言·托管
青山木10 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
传奇开心果编程12 小时前
【Rust入门练中学】 第3课:数据类型
开发语言·学习·rust
这料鬼有毒12 小时前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划
泡泡鱼(敲代码中)12 小时前
MySQL 学习笔记:DCL、函数与约束 —— 安全、效率、完整性的三板斧
开发语言·笔记·sql·学习·mysql·gitee
政企项目老覃13 小时前
边缘 AI 推理部署:安防零售场景下的模型裁剪与端侧落地实践
人工智能·程序人生·算法·性能优化·vllm
I_belong_to_jesus13 小时前
std::unique_ptr成员函数用法
c++
爱吃苹果的日记本13 小时前
数据结构第五课
数据结构·学习
Tairitsu_H13 小时前
[C++] 拷贝构造还是赋值重载?类默认成员函数细节详解
开发语言·c++·类和对象