您的位置:首页 > 其它

[LeetCode] Word Search

2014-09-14 16:03 260 查看

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 =

[
["ABCE"],
["SFCS"],
["ADEE"]
]

word =
"ABCCED"
, -> returns
true
,

word =
"SEE"
, -> returns
true
,

word =
"ABCB"
, -> returns
false
.

题解:本题很显然可以采用递归的思路来解,可关键点在于当发现word中某个字符和board中某个位置的字符相同时,接下来的路应该怎么走,因为有可能会存在某些方向上相邻的字符已经被比较过,所以这里需要一个辅助存储用于记录word是否走过该位置。

代码如下:

public class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 || board[0].length == 0)
return false;

int rows = board.length;
int cols = board[0].length;
boolean[][] used = new boolean[rows][cols];

for(int i = 0; i < rows; i++){
for(int j = 0; j < cols ; j++){
if(search(board, word, 0, i, j, used))
return true;
}
}
return false;
}

private boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used){
if(index == word.length())
return true;
if(i >= board.length || j >= board[0].length || i < 0 || j < 0 || used[i][j] || word.charAt(index) != board[i][j])
return false;

used[i][j] = true;
boolean result = 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 result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: