您的位置:首页 > 其它

79 Word Search

2015-10-28 21:23 288 查看
题目链接:https://leetcode.com/problems/word-search/

题目:

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.


解题思路:

这道题考点在图的深度遍历

而我只能想到是递归。虽然图的深度遍历也是利用递归来解答,但是解题思路的高度就低了不少,,而且做题时还忽略了不能查找已经遍历过的元素,这一点很关键地点名了图的特性。

在 code ganker 大神的带领下终于找到解决方案。这实际上就是除了边界上的节点,每个节点都有 4 条边这样一个图,然后对其深度遍历,查找指定的字符串。

大神参考链接:/article/1378240.html

特别注意:对于每一道题,首先要知道它的考点,再具体化算法,再动手写代码,否则写半天也写不对!!!

代码实现:

public class Solution {
public boolean exist(char[][] board, String word) {
if(word == null || word.length() == 0)
return true;
if(board == null || board.length == 0 || board[0].length == 0)
return false;
boolean[][] used = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i ++) {
for(int j = 0; j < board[0].length; j ++) {
if(search(board, word, 0, i, j, used))
return true;
}
}
return false;
}
boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used) {
if(index == word.length())
return true;
if(i < 0 || i > board.length - 1 || j < 0 || j > board[0].length - 1 || used[i][j] || word.charAt(index) != board[i][j])
return false;
used[i][j] = true;
boolean res = search(board, word, index + 1, i - 1, j, used)
|| search(board, word, index + 1, i + 1, j, used)
|| search(board, word, index + 1, i, j - 1, used)
|| search(board, word, index + 1, i, j + 1, used);
used[i][j] = false;
return res;
}
}


83 / 83 test cases passed.
Status: Accepted
Runtime: 11 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: