Word Search
2015-10-02 16:25
239 查看
题目:
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 =
word =
-> returns
word =
-> returns
word =
-> returns
分析:
dfs
参考代码:
http://www.programcreek.com/2014/06/leetcode-word-search-java/
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
参考代码:
http://www.programcreek.com/2014/06/leetcode-word-search-java/
public class Solution { public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean result = false; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(dfs(board,word,i,j,0)){ result = true; } } } return result; } public boolean dfs(char[][] board, String word, int i, int j, int k){ int m = board.length; int n = board[0].length; if(i<0 || j<0 || i>=m || j>=n){ return false; } if(board[i][j] == word.charAt(k)){ char temp = board[i][j]; board[i][j]='#'; if(k==word.length()-1){ return true; }else if(dfs(board, word, i-1, j, k+1) ||dfs(board, word, i+1, j, k+1) ||dfs(board, word, i, j-1, k+1) ||dfs(board, word, i, j+1, k+1)){ return true; } board[i][j]=temp; } return false; } }
相关文章推荐
- ocp-34
- Node.js第三方库之request
- 滑动窗口的最大值
- POJ1815 Friendship(字典序最小最小割割边集)
- Linux 命令 - head: 打印文件的开头部分
- 【HDOJ】4513 吉哥系列故事——完美队形II
- 如何用tomcat配置虚拟目录,方法要详细明了
- JAVA实现链表中倒数第K个节点问题(《剑指offer》)
- poj 3580 splay
- 《php和mysql web开发》笔记——第10章 使用MySQL数据库
- jackson 解析结合类(需要传入Class, 和 Class.Class, 回调方法是List<Class>)
- hdu 4813(2013长春现场赛A题)
- Hibernate懒加载
- Python基础
- 03 crawler
- ocp-33
- [LeetCode][JavaScript]Reverse Linked List II
- 栈——括号匹配
- ocp-32
- HDU 2100 模拟