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;
    }
};
相关推荐
程与留11 小时前
15_国际化和本地化:tr()、ts 文件、QM 文件、多语言切换
c++·qt
地平线开发者12 小时前
【模型轻量化专题】衡量模型轻量性的指标
算法
程与留12 小时前
14_Qt 样式表(QSS)入门(语法、选择器、美化实战)
c++·qt
学习星球15 小时前
OFDM技术精讲:正交性推导、循环前缀原理与80行Python链路仿真(附实测数据)
算法·面试·前端框架
欧特克_Glodon21 小时前
OpenCV计算机视觉开发入门与实践<二十七>:图像分割概述
c++·人工智能·opencv·计算机视觉
蒸蒸yyyyzwd21 小时前
cpp 选手秋招学习笔记 day21
c++·面试·八股
alphaTao21 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
Interview Aid11221 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt1 天前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
顶点多余1 天前
那些在算法中适合巩固的知识点---1
java·前端·算法