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;
    }
};
相关推荐
写代码写到手抽筋1 小时前
5G上行DCI字段判定:端口 流数 PMI选择详解
java·算法·5g
xieliyu.1 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
苏宸啊2 小时前
IPC管道
linux·c++
何以解忧,唯有..2 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
BestOrNothing_20152 小时前
ROS2 话题通信实战:消息对象、Publisher 发布器与 Subscriber 订阅器保姆级教程
c++·ros2·subscriber·publisher·话题通信
wayz112 小时前
Momentum:PSL(心理线指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
雪的季节2 小时前
RabbitMQ详解
开发语言
8Qi83 小时前
LeetCode 213:打家劫舍 II(House Robber II)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
ice8130331813 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
三品吉他手会点灯3 小时前
C语言学习笔记 - 44.运算符和表达式 - 运算符2 - 除法与取余运算符
c语言·开发语言·笔记·算法