lintcode --单词搜索
来源:互联网 发布:历代windows 编辑:程序博客网 时间:2024/05/23 02:01
给出一个二维的字母板和一个单词,寻找字母板网格中是否存在这个单词。
单词可以由按顺序的相邻单元的字母组成,其中相邻单元指的是水平或者垂直方向相邻。每个单元中的字母最多只能使用一次。
给出board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED", ->返回 true,
word = "SEE",-> 返回 true,
word = "ABCB", -> 返回 false.
/*
[
["ABCE"],
["SFCS"],
["ADEE"]
]
思路
1.基本思路很简单,对矩阵里每个点都进行一次深度优先搜索,看它能够产生一个路径和所给的字符串是一样的。
2.重点在如何优化搜索,避免不必要的计算。比如我们一个方向的搜索中已经发现了这个词,那我们就不用再搜索。
3.另外,为了避免循环搜索,我们还要将本轮深度优先搜索中搜索过的数字变一下,等递归回来之后再变回来。
实现这个特性最简单的方法就是异或上一个特定数,然后再异或回来。*///博客
public class Solution {
public boolean exist(char[][] board, String word) {
if(board.length == 0) return false;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
// 从i,j点作为起点开始搜索
boolean isExisted = search(board, i, j, word, 0);
if(isExisted==true) return true;
}
}
return false;
}
private boolean search(char[][] board, int i, int j, String word, int idx){
if(idx >= word.length()) return true;
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length
|| board[i][j] != word.charAt(idx)) {
return false;
}else{//board[i][j] == word.charAt(idx)
// 将已经搜索过的字母标记一下,防止循环。变成另外一个字符,就不会再循环
board[i][j] ^= 255;
}
boolean res = search(board, i-1, j, word, idx+1)
|| search(board, i+1, j, word, idx+1)
|| search(board, i, j-1, word, idx+1)
|| search(board, i, j+1, word, idx+1);
// 再次异或255就能恢复成原来的字母
board[i][j] ^= 255;
return res;
}
}
- lintcode-单词搜索-123
- lintcode ----单词搜索
- LintCode 单词搜索 II
- LintCode : 单词搜索 II
- lintcode,单词搜索
- 单词搜索 -LintCode
- 单词搜索 II-LintCode
- lintcode --单词搜索
- LintCode 120-单词接龙 广度优先搜索
- LintCode 132-单词搜索II 深度优先
- DFS-lintcode单词搜索(word-search)
- LintCode 最长单词
- lintcode-单词接龙-120
- 最长单词(LintCode)
- LintCode- 单词切分
- lintcode ----最长单词
- LintCode 单词切分
- lintcode,单词切分
- VS2008(10及以上版本)opencv2.413的配置
- Hybrid Crystals(HDU 6140)
- 构建APP下载的landpage
- 一个nodejs在线编程题目做为此类参考
- Killer Names (HDU6143 17多校赛)
- lintcode --单词搜索
- 实现CKEDITOR图像浏览与上传
- you-get 使用总结
- zabbix监控MySQL部署实战
- [RK3288][Android6.0] 调试笔记 --- jpeg硬件解码测试
- 平均成绩
- the comprehensive description abut ‘copy’ and 'deepcopy' in python
- VS2010 cannot convert parameter 1 from 'char *' to 'LPCWSTR'
- Webstorm 激活与汉化