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 = board[i].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;
    }
};
相关推荐
fox_lht1 小时前
第一章 不可变的变量
开发语言·后端·rust
骁的小小站2 小时前
Verilator 和 GTKwave联合仿真
开发语言·c++·经验分享·笔记·学习·fpga开发
心灵宝贝4 小时前
申威架构ky10安装php-7.2.10.rpm详细步骤(国产麒麟系统64位)
开发语言·php
lly2024064 小时前
PHP 字符串操作详解
开发语言
大数据张老师4 小时前
数据结构——邻接矩阵
数据结构·算法
低音钢琴5 小时前
【人工智能系列:机器学习学习和进阶01】机器学习初学者指南:理解核心算法与应用
人工智能·算法·机器学习
像是套了虚弱散5 小时前
DevEco Studio与Web联合开发:打造鸿蒙混合应用的全景指南
开发语言·前端·华为·harmonyos·鸿蒙
旭意5 小时前
C++蓝桥杯之结构体10.15
开发语言·c++
深思慎考6 小时前
调用百度云语音识别服务——实现c++接口识别语音
c++·语音识别·百度云
麦麦鸡腿堡7 小时前
Java的单例设计模式-饿汉式
java·开发语言·设计模式