当前位置: 首页 > news >正文

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?

二、题解

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;}
};
http://www.lryc.cn/news/298565.html

相关文章:

  • Linux命令-blkid命令(查看块设备的文件系统类型、LABEL、UUID等信息)
  • 服务治理中间件-Eureka
  • Javaweb之SpringBootWeb案例之异常处理功能的详细解析
  • 苹果Mac键盘如何将 F1 到 F12 取消按Fn
  • linux下ipconfig命令报:command not found 解决方法
  • Android导入其它项目慢,Gradel下载失败,另辟蹊径:使用离线gradle加载,附镜像方式
  • 神经语言程式(NLP)项目的15 个开源训练数据集
  • H5 红色文字抖动网址发布页/引导页源码
  • MacOS - 菜单栏上显示『音量』
  • 深入理解常见的设计模式
  • 服务器解析漏洞及任意文件下载
  • ES6扩展运算符——三个点(...)用法详解
  • 限制资源使用
  • 结合Next项目实际认识webpack.splitChunks
  • 【Tauri】(2):使用Tauri应用开发,使用开源的Chatgpt-web应用做前端,使用rust 的candle做后端,本地运行小模型桌面应用
  • C#where T :通用的泛型约束(generic constraint)语法
  • vue使用Mars3d弹框嵌套video视频/实时视频(m3u8)使用hls.js
  • Python爬虫之Ajax数据爬取基本原理
  • osg操控器和键盘切换操控器学习
  • LeetCode1143. Longest Common Subsequence——动态规划
  • 利用Windows10漏洞破解密码(保姆级教学)
  • apk反编译修改教程系列---简单修改apk默认横竖屏显示 手机端与电脑端同步演示【十一】
  • 2301: 不定方程解的个数
  • vue3学习——封装菜单栏
  • 深度学习的进展及其在各领域的应用
  • blender怎么保存窗口布局,怎么设置默认输出文件夹
  • 【开源】基于JAVA+Vue+SpringBoot的实验室耗材管理系统
  • 【ES】--Elasticsearch的分词器详解
  • 【算法】{画决策树 + dfs + 递归 + 回溯 + 剪枝} 解决排列、子集问题(C++)
  • sqlserver 存储过程