题目地址:
https://www.lintcode.com/problem/word-search/description
给定一个只含英文字母的 m × n m\times n m×n矩阵,再给定一个字符串 s s s,问矩阵中是否存在一个路径,使得路径上的字符依次正好构成了那个字符串。路径的每一步只能走到上下左右相邻的格子里去,每个格子只能访问一次。
思路是DFS。用一个整数标记当前已经走到了字符串的哪一个位置,然后从当前格子尝试向四个方向走一步,也就是进入下一层递归。直到走到了字符串的最后一个字符仍然没有矛盾,则返回true。代码如下:
public class Solution {
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
public boolean exist(char[][] board, String word) {
// write your code here
if (word == null || word.isEmpty()) {
return false;
}
// 二维矩阵的四个方向上的单位向量
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// 记录已经走过的格子。因为不能重复走,所以要进行标记
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 (dfs(board, word, 0, i, j, visited, dirs)) {
return true;
}
}
}
return false;
}
// 从board[x][y]开始走,判断是否存在路径等于word。其中board[x][y]对应word[pos]
private boolean dfs(char[][] board, String word, int pos, int x, int y, boolean[][] visited, int[][] dirs) {
// 如果字符不对应,直接返回false
if (board[x][y] != word.charAt(pos)) {
return false;
}
// 如果字符对应,且该字符已经是字符串的最后字符了,那就返回true
if (pos == word.length() - 1) {
return true;
}
// 标记当前格子访问过
visited[x][y] = true;
for (int i = 0; i < dirs.length; i++) {
// 枚举四个方向走一步
int nextX = x + dirs[i][0], nextY = y + dirs[i][1];
// 如果走一步的格子之前没有访问过,则判断这一步是否可能产生合法的路径
if (inBoard(board, nextX, nextY) && !visited[nextX][nextY]) {
// 从下一个格子开始继续走,如果能走出合法路径,则返回true
if (dfs(board, word, pos + 1, nextX, nextY, visited, dirs)) {
return true;
}
}
}
// 尝试完四个方向仍然走不出合法路径,则返回false;
// 返回之前要记得回溯,恢复现场
visited[x][y] = false;
return false;
}
private boolean inBoard(char[][] board, int x, int y) {
return 0 <= x && x < board.length && 0 <= y && y < board[0].length;
}
}
时间复杂度 O ( m n 3 l s ) O(mn3^{l_{s}}) O(mn3ls), l l l为字符串长度,每次可选的方向有 3 3 3个(因为不能回退),空间复杂度 O ( m n ) O(mn) O(mn)。