题目
给定一个2D的网格字符,一个单词字符串。找到这个单词是否在2D网格字符中存在。
这个词可以从2D网格的邻近字符中去构建,包括垂直和水平方向上。在构建单词时相同的字符不可超过一次。
如,2D board的值如下:
[
["ABCE"],
["SFCS"],
["ADEE"]
]
期望结果
word = "ABCCED", -> returns true
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
java实现
这个题目可以通过dfs进行实现
public class WordSearch {
public static boolean exist(char[][] board,String word) {
String result = "";
for (int i = 0;i < board.length;i ++) {
for (int j = 0;j < board[0].length;j ++) {
boolean v = dfs(board,i,j,word,result);
if (v) {
return true;
}
}
}
return false;
}
private static boolean dfs(char[][] board,int i,int j,String word,String result) {
if (i < 0 || j >= board[0].length || j < 0 || i >= board.length || board[i][j] =='#') {
return false;
}
result = result + board[i][j];
if (result.length() > word.length()) {
return false;
}
if (result.equals(word)) {
return true;
}
else {
char temp = board[i][j];
board[i][j] = '#';
if ((dfs(board,i-1,j,word,result) || dfs(board,i+1,j,word,result)
|| dfs(board,i,j-1,word,result) || dfs(board,i,j+1,word,result))) {
return true;
}
board[i][j] = temp;
return false;
}
}
public static void main(String[] args) {
char[][] board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
String word = "SEE";
System.out.println(exist(board,word));
}
}