LeetCode Word Search
来源:互联网 发布:淘宝网民族风棉麻棉裤 编辑:程序博客网 时间:2024/09/21 06:22
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.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word = "ABCB"
, -> returns false
.
思路分析:这题可以用DFS 搜索解决,但是实现当中有几个地方要注意。首先dfs函数需要维护已经访问过的位置标记数组,当前搜索的位置,当前匹配的word里面char的位置。其次,对于边界条件,标记条件的判断有时放在递归调用之前比较方便,有时放在递归调用之后进入递归函数后的开头部分比较方便,这题属于后者,由于要搜索四个方向,搜索在递归调用前不做越界判断,而在进入递归函数后进行判断,如果越界返回false这样更容易实现。第三,应该尝试以棋盘的每个位置为起点进行搜索。第四,当且仅当四个方向搜索全部返回false,当前dfs函数才返回false,并且返回之前要注意恢复现场,这就是程序中第26行到第28行所对应。visited数组传入dfs函数后内容发生过改变,但是每次都恢复现场给还原成了false,因此,换新起点重新搜索是visited数组已经全部为false,不需要初始化。
AC Code
- public class Solution {
- public boolean exist(char[][] board, String word) {
- int m = board.length;
- if(m == 0) {
- if(word.isEmpty()) return true;
- else return false;
- }
- int n = board[0].length;
- char [] wordArray = word.toCharArray();
- int len = wordArray.length;
- boolean [][] visited = new boolean[m][n];
- for(int i = 0; i < m; i++){
- for(int j = 0; j < n; j++){
- if(dfs(board, wordArray, 0, i, j, visited, m, n)) return true;
- }
- }
- return false;
- }
- boolean dfs(char [][] board, char [] wordArray, int curIndex, int i, int j, boolean[][] visited, int m, int n){
- if(curIndex >= wordArray.length) return true;
- if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] != wordArray[curIndex]){
- return false;
- }
- curIndex++;
- visited[i][j] = true;
- boolean flag = dfs(board, wordArray, curIndex, i-1, j, visited, m, n) || dfs(board, wordArray, curIndex, i+1, j, visited, m, n) || dfs(board, wordArray, curIndex, i, j-1, visited, m, n) || dfs(board, wordArray, curIndex, i, j+1, visited, m, n);
- visited[i][j] = false;// restore the state
- return flag;
- }
- }
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- ME3760_v2驱动移植方式,中兴4G网卡移植
- MATLAB矩阵操作命令
- Windows上快速创建一个1G以上的大文件
- HADOOP和Spark统计SRS的代码的单词频率
- source insight中集成pclint
- LeetCode Word Search
- JAVA编程思想学习总结:第21章第4节终结与协作
- Ubuntu 查看和杀死进程
- 胜者树和败者树的讲解
- 黑马程序员——java基础项目:交通灯管理系统项目实战
- 关于范式的一些笔记
- 正则表达式?的用法
- Android LayoutInflater原理分析
- Struts2入门篇-- 用户登录