Word Search
2015-11-17 16:37
155 查看
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.
Subscribe to see which companies asked this question
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.
Subscribe to see which companies asked this question
public class Solution { //this is a good problem public boolean exist(char[][] board, String word) { if(board == null || word == null || word.length() == 0) return false; for(int i =0; i < board.length; i ++) { for(int j = 0; j < board[0].length; j++) { if(dfs(board, i, j, word, 0, new boolean[board.length][board[0].length])) return true; } } return false; } private boolean dfs(char[][] board, int i, int j, String word, int index, boolean[][] isVisited) { if(word.length() == index) return true; if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index) || isVisited[i][j]) return false; isVisited[i][j] = true; if(dfs(board, i - 1, j, word, index + 1, isVisited)) return true; if( dfs(board, i + 1, j, word, index + 1, isVisited)) return true; if( dfs(board, i, j - 1, word, index + 1, isVisited)) return true; if( dfs(board, i, j + 1, word, index + 1, isVisited)) return true; //this statement is equal to the four statement above // boolean res = dfs(board, i - 1, j, word, index + 1, isVisited) || dfs(board, i + 1, j, word, index + 1, isVisited) || // dfs(board, i, j - 1, word, index + 1, isVisited) || dfs(board, i, j + 1, word, index + 1, isVisited); isVisited[i][j] = false; return false; // return res; } }
相关文章推荐
- ubuntu12.04LTS+Qt4.8.6+opencv2.4.9
- Mybatis入门
- Windows中使用cmd实现自定义Service的安装与卸载
- Windows Server 2008 DNS服务器安装与配置
- Fatal error: Class 'ZipArchive' not found的解决办法
- 老李分享:qtp自动化测试框架赏析-关键字自动化测试框架
- QML之Menu菜单
- Android下通过wpa_supplicant来测试wifi设备
- 《增长黑客》——干货迭出
- cocos2dx之Lua调用C++
- Linux定时器与延时
- lightOj1006 Hex-a-bonacci
- host is not allowed to connect to this MySql server
- iOS相册图片的选取与设置
- POI教程-简单操作
- cocos2dx之Lua调用C++
- 打杂程序员之ftp换成外网ip咋就登陆不上?
- fopen()函数文件模板中w,w+,a,a+的区别
- 修改代码一般在测试服务器
- 通过方法名字符串调用方法