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.
Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
tag : array, backtracking
method 1
使用一个访问辅助数组,在每次访问时置为true,如果这次访问没有得到完整的目标word,就再把辅助访问数组对应的值置为false
boolean[][] visit;
public boolean exist(char[][] board, String word) {
visit = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (exist2(board, word, 0, i, j))
return true;
}
}
}
return false;
}
private boolean exist(char[][] board, String word, int index, int i, int j) {
if (index == word.length())
return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length || visit[i][j] || board[i][j] != word.charAt(index) || visit[i][j])
return false;
visit[i][j] = true;
if (exist(board, word, index + 1, i + 1, j) || exist(board, word, index + 1, i, j + 1) || exist(board, word, index + 1, i - 1, j) || exist(board, word, index + 1, i, j - 1))
return true;
visit[i][j] = false;
return false;
}
method 2
可以对method 1 进行优化,使得空间复杂度变为O(1)
即在访问时,将该位置的字符置为其他不存在干扰的字符,当访问结束没有得到完整的目标word时,再置回,运用了位操作
private boolean exist2(char[][] board, String word, int index, int y, int x) {
if (index == word.length()) return true;
if (y < 0 || x < 0 || y == board.length || x == board[y].length) return false;
if (board[y][x] != word.charAt(index)) return false;
board[y][x] ^= 256;
boolean exist = exist(board, word, index + 1, y, x + 1)
|| exist(board, word, index + 1, y, x - 1)
|| exist(board, word,index+1,y + 1, x)
|| exist(board, word,index+1,y - 1, x);
board[y][x] ^= 256;
return exist;
}
summary:
- 需要记录访问呢轨迹时,使用一个访问数组,并且在这个分支回溯完成后,把访问数组中该位置置回原来的值
- 也可以不用访问数组,那么就必须标记这个位置的数已经被访问过,可以
- 使用其他根本不会干扰的字符,结束之后再置回原来的数,使用位操作^256
- 在不会再被访问的位置标记该数(见73)