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;
    }
};
相关推荐
Blossom.1185 小时前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
轻微的风格艾丝凡5 小时前
卷积的直观理解
人工智能·深度学习·神经网络·算法·计算机视觉·matlab·cnn
武子康7 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
田梓燊7 小时前
红黑树分析 1
算法
晚风吹长发8 小时前
二分查找算法+题目详解
c++·算法·二分查找
悠悠~飘8 小时前
18.PHP基础-递归递推算法
算法·php
怪兽20148 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang8 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志8 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友8 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php