問題:
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”, 即匹配方向是連續(xù)的,不走回頭路。
因而這個問題暴力遞歸便可。
代碼示例:
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周繼續(xù)匹配
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;
}
}