LeetCode剑指 Offer 12. 矩阵中的路径
题目描述
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 “ABCCED”(单词中的字母已标出)。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
题解
递归回溯
在回溯方法backTrack
中,为了简化参数,字符串单词传入的是word
的子集word.substring(1)
,但是这样时间效率较低。
class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(word.charAt(0) == board[i][j]) {
if(backTrack(board, word, i, j))
return true;
}
}
}
return false;
}
public boolean backTrack(char[][] board, String word, int row, int col) {
if(word.length() == 0) return true;
if(row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false;
if(word.charAt(0) != board[row][col] || board[row][col] == '#') return false;
char temp = board[row][col];
board[row][col] = '#';
boolean ans = backTrack(board, word.substring(1), row+1, col)
|| backTrack(board, word.substring(1), row-1, col)
|| backTrack(board, word.substring(1), row, col+1)
|| backTrack(board, word.substring(1), row, col-1);
board[row][col] = temp;
return ans;
}
}
执行结果
时间优化版
通过修改word的类型为数组
和增加传入参数index
来增加时间效率。
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if (backTrack(board, words, i, j, 0))
return true;
}
}
return false;
}
boolean backTrack(char[][] board, char[] word, int i, int j, int index) {
if (index == word.length) return true;
if (i >= board.length || i < 0 || j >= board[0].length || j < 0 ) return false;
if (word[index] != board[i][j] || board[i][j] == '#') return false;
char tmp = board[i][j];
board[i][j] = '#';
boolean res = backTrack(board, word, i + 1, j, index + 1)
|| backTrack(board, word, i - 1, j, index + 1)
|| backTrack(board, word, i, j + 1, index + 1)
|| backTrack(board, word, i, j - 1, index + 1);
board[i][j] = tmp;
return res;
}
}
执行结果
数组
效率明显比String
要高
若word
的传入类型为String
class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if (backTrack(board, word, i, j, 0))
return true;
}
}
return false;
}
boolean backTrack(char[][] board, String word, int i, int j, int index) {
if (index == word.length()) return true;
if (i >= board.length || i < 0 || j >= board[0].length || j < 0 ) return false;
if (word.charAt(index) != board[i][j] || board[i][j] == '#') return false;
char tmp = board[i][j];
board[i][j] = '#';
boolean res = backTrack(board, word, i + 1, j, index + 1)
|| backTrack(board, word, i - 1, j, index + 1)
|| backTrack(board, word, i, j + 1, index + 1)
|| backTrack(board, word, i, j - 1, index + 1);
board[i][j] = tmp;
return res;
}
}
执行结果