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;
    }
};
相关推荐
码爸6 小时前
线性回归算法
算法·机器学习·线性回归
kimnoic6 小时前
Python数据库学习心得:SQLite、MySQL、PostgreSQL优缺点
开发语言·python
Coder-magician7 小时前
《代码随想录》刷题打卡day51:图论-part09(dijistra堆优化,Bellman_ford算法)
算法·图论
Nil2087 小时前
leetcode 763划分字母区间
算法·leetcode·职场和发展
不会就选b7 小时前
算法日常・每日刷题--<动态规划>20
算法·leetcode·动态规划
别动我齐刘海7 小时前
C++ 工程化学习
java·linux·前端·c++·学习·机器学习·机器人
程序员老陆7 小时前
C++ std::promise深度解析
c++·程序设计
必须得开心呀7 小时前
python编写带界面的软件,需要安装哪些插件
开发语言·python
青少儿编程课堂8 小时前
迪杰斯特拉(Dijkstra)算法:单源最短路与赛场路线规划
c++·python·算法·bfs·信息学竞赛
不会就选b8 小时前
算法日常・每日刷题--<动态规划>19
算法·leetcode·职场和发展