[LeetCode] 79. Word Search
来源:互联网 发布:深圳棋牌网络开发公司 编辑:程序博客网 时间:2024/06/12 08:46
【原题】
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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
【解释】
给定一个二维的字符数组和一个单词,要求返回该单词是否可以在该字符数组中找到(查找尽可以上下左右查找)
【思路】
从数组的每一个位置上下左右递归查找,如果有任意方向找到则返回true,否则从下一个位置开始查找。
public class Solution { public static boolean exitCore(char[][] board,String word, int index, int row,int col,boolean[][] isVisit){ if(index==word.length()) return true;//前面所有的元素都相等,则找到 if(row<0||col<0||row>=board.length||col>=board[0].length|| board[row][col]!=word.charAt(index)||isVisit[row][col]) return false; boolean flag=false; isVisit[row][col]=true; flag=exitCore(board, word, index+1,row+1,col,isVisit)||exitCore(board, word, index+1,row,col+1,isVisit) ||exitCore(board, word, index+1,row-1,col,isVisit)||exitCore(board, word, index+1,row,col-1,isVisit); if(flag) return flag; isVisit[row][col]=false;//没有找到,重新将该元素置为未访问 return false; } public static boolean exist(char[][] board, String word) { int m=board.length,n=board[0].length; boolean[][] isVisit=new boolean[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++) if(exitCore(board,word,0,i,j,isVisit)) return true; } return false; }}
阅读全文
0 0
- LeetCode 79. Word Search
- [LeetCode]79.Word Search
- LeetCode --- 79. Word Search
- [Leetcode] 79. Word Search
- [leetcode] 79.Word Search
- 【leetcode】79. Word Search
- [LeetCode]79. Word Search
- 79. Word Search LeetCode
- leetcode 79. Word Search
- LeetCode 79. Word Search
- LeetCode 79. Word Search
- leetcode 79. Word Search
- LeetCode *** 79. Word Search
- [leetcode] 79. Word Search
- LeetCode-79.Word Search
- Leetcode 79. Word Search
- LeetCode - 79. Word Search
- [LeetCode] 79. Word Search
- Android全局异常捕获机制
- 电源的输出纹波噪声究竟该取多少才合适?
- 使用mysql自带函数注意事项
- 【机器学习】coursera学习笔记(一)
- BZOJ1012(JSOI2008)[最大数maxnumber]--线段树区间极值
- [LeetCode] 79. Word Search
- LCD驱动快速调试
- Ubuntu的启动栏:左边还是下边
- 非旋转treap模板
- [noip2009]: 最优贸易
- 原生JS实现选项卡效果实例
- waitpid函数的使用
- Unity中状态机的使用
- php-11