https://oj.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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
public boolean exist(char[][] board, String word)
这一题和后面有一题叫surrounded region的是有点类似的,本质是图论题。在每个点进行图的遍历,BFS或者DFS皆可。这一题首选DFS深度搜索,因为我们需要找到的是唯一一个单词,也就是深度搜索到一个路径匹配那个word就可以返回true了。BFS广度搜索更适合搜寻所有的路径,也就是这一题如果要求返回的不是boolean而是所有符合word的东西的话,广度搜索就会更加适合,所以在surrounded region那题我就用了BFS。另外这类题都需要用一种方式标记自己走过的地方,这里用的就是一个二维boolean矩阵,DFS比BFS便利的地方也在于它们比较容易维护和回收自己走过节点的标记。这样就不需要另外维护走过的标记
public boolean exist(char[][] board, String word) {
boolean[][] visited = 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(helper(visited, board, i, j, 0, word))
return true;
}
}
return false;
}
public boolean helper(boolean[][] visited, char[][] board, int x, int y, int cur_len, String word){
if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y])
return false;
if(word.charAt(cur_len) == board[x][y]){
if(cur_len == word.length() - 1)
return true;
visited[x][y] = true;
if(helper(visited, board, x - 1, y, cur_len + 1, word) || helper(visited, board, x + 1, y, cur_len + 1, word) || helper(visited, board, x, y + 1, cur_len + 1, word) || helper(visited, board, x, y - 1, cur_len + 1, word))
return true;
visited[x][y] = false;
return false;
}else
return false;
}
Updated 12-09-2018 :
下面给出一个非常tricky的in place的方案。主要是在于^=256 改变了当前值,作为一种visited的标记,然后再用^=256作为异或复原值的一种手段,
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (boardHelper(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean boardHelper(char[][] board, String word, int x, int y, int curPos) {
if (curPos == word.length()) return true;
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || word.charAt(curPos) != board[x][y]) return false;
board[x][y] ^= 256;
boolean result = boardHelper(board, word, x + 1, y, curPos + 1)
|| boardHelper(board, word, x, y + 1, curPos + 1)
|| boardHelper(board, word, x - 1, y, curPos + 1)
|| boardHelper(board, word, x, y - 1, curPos + 1);
board[x][y] ^= 256;
return result;
}