问题:
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.
注意题干的“sequentially”, 即匹配方向是连续的,不走回头路。
因而这个问题暴力递归便可。
代码示例:
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null) {
return false;
}
//用于记录每一个字符是不是已匹配过
boolean[][] bitMap = 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 (existInner(board, i, j, bitMap, word, 0)) {
return true;
}
}
}
return false;
}
private boolean existInner(char[][] board, int i, int j, boolean[][] bitMap, String word, int next) {
//匹配终了
if (next == word.length()) {
return true;
}
if (i >= board.length || i < 0 || j >= board[0].length || j < 0) {
return false;
}
//不相等,或已匹配过
if (board[i][j] != word.charAt(next) || bitMap[i][j]) {
return false;
}
bitMap[i][j] = true;
//向当前位置的4周继续匹配
boolean rst = existInner(board, i+1, j, bitMap, word, next+1) ||
existInner(board, i-1, j, bitMap, word, next+1) ||
existInner(board, i, j+1, bitMap, word, next+1) ||
existInner(board, i, j-1, bitMap, word, next+1);
if (!rst) {
//需要复位
bitMap[i][j] = false;
}
return rst;
}
}