[抄题]:

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
] Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

一般的dfs都是主函数中调用一次就行了。搜索单词时,每个点都要调,因为每个点都有可能成为起点。

[一句话思路]:

单词的回溯法是dfs的一种,模式是:访问过-扩展-没访问过

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

单词的回溯法是dfs的一种,模式是:访问过-扩展-没访问过

[复杂度]:Time complexity: O(4^n) Space complexity: O(n^2)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

每个点都有可能开始:

//for loop
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (word.charAt(0) == board[i][j] && backtrace(board, i, j, word, 0)) return true;
}
}

boolean == true不用写,就是默认== true

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

2: trie树

[代码风格] :

class Solution {
static boolean[][] visited;
public boolean exist(char[][] board, String word) {
//ini:visited
visited = new boolean[board.length][board[0].length]; //for loop
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (word.charAt(0) == board[i][j] && backtrace(board, i, j, word, 0)) return true;
}
} return false;
} public boolean backtrace(char[][] board, int i, int j, String word, int index) {
//length
if (index == word.length()) return true; //exit:range, not equal, visited
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length ||
word.charAt(index) != board[i][j] || visited[i][j]) return false; //expand
visited[i][j] = true;
if (backtrace(board, i + 1, j, word, index + 1) ||
backtrace(board, i - 1, j, word, index + 1) ||
backtrace(board, i, j + 1, word, index + 1) ||
backtrace(board, i, j - 1, word, index + 1)) return true;
visited[i][j] = false; return false;
}
}

最新文章

  1. Java之控制反转和依赖注入
  2. 关于for,while与do while
  3. 从链接上获取参数值, location.href上获取参数
  4. 信号之sigsuspend函数
  5. POJ1015 动态规划
  6. Web框架-Django基础
  7. java中需要注意的小细节
  8. [ 搭建Redis本地服务器实践系列一 ] :图解CentOS7安装Redis
  9. spring mvc 在上传图片时,浏览器报The request sent by the client was syntactically incorrect
  10. python学习2---交换两个元素
  11. Spring Boot 定时任务使用
  12. LINUXJI积算器bc
  13. Linux日常使用命令
  14. p1218 Superprime Rib
  15. Halcon常用算子01
  16. 代码实现SQL SERVER TCP/IP协议配置
  17. 20145332卢鑫 WEB安全基础实验
  18. log4net保存到数据库系列二:独立配置文件中配置log4net
  19. aws存储桶s3使用
  20. Android SDK的安装教程

热门文章

  1. 13.Python接口自动化测试 -- 豆瓣
  2. nginx虚拟机的配置
  3. Docker的一些常用
  4. Codeforces 982C(dfs+思维)
  5. Go - 开始
  6. user
  7. python学习笔记(十):操作excel
  8. svn关键词BASE, HEAD, COMMITTED, PREV的深入理解
  9. 构造方法PK实例方法
  10. 「小程序JAVA实战」swagger2的使用与接口测试(34)