题目要求
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
思路:
- 从board的(0,0)位置出发,依次向上向下向左向右遍历,看遍历到的元素是否和word相应的位置元素相等,在此过程中记录表示word下标的指针index,若index >= word.length(),则说明找到了一条路径。
- 同时,由于题目中要求 同一个单元格内的字母不允许被重复使用 所以使用和board等大小的visited数组标识,从当前位置出发访问过board的元素相应的在visited中设置为true。
- (但是在递归的过程中需要恢复现场,因为假设在(0,0)位置开始查找时visited[0][0] 设置为true,表示已经被访问过,但是再从board中(0,1)位置开始时,(0,0)应该是没有被访问过的状态。)
public class WordSearch {
public boolean exist(char[][] board, String word) {
int N = board.length;
int M = board[0].length;
char[] words = word.toCharArray();
boolean[][] visited = new boolean[N][M]; // 记录在当前递归中该元素是否被访问过
// 需要从board中的每个字符中尝试
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
boolean res = process(board,words,visited,i,j,0);
if (res) {
return true;
}
}
}
return false;
}
private boolean process(char[][] board, char[] words, boolean[][] visited, int curX, int curY, int index) {
if (index >= words.length) {
return true;
}
// 剪枝
if (curX < 0 || curY < 0 || curX >= board.length || curY >= board[0].length || board[curX][curY] != words[index] || visited[curX][curY] == true) {
return false;
}
visited[curX][curY] = true;
boolean res = process(board, words, visited, curX + 1, curY,index + 1) ||
process(board, words, visited,curX - 1,curY,index + 1) ||
process(board, words, visited, curX,curY - 1, index + 1) ||
process(board, words, visited, curX, curY + 1, index + 1);
visited[curX][curY] = false; // 恢复现场
return res;
}
}
最后提交结果: