One, the problem
1. Description
Please design a function to judge whether there is a path containing all characters of a string in a matrix. The path can start from any grid in the matrix, and each step can move one grid to the left, right, up, and down in the matrix. If a path passes through a grid of the matrix, the path cannot enter the grid again. For example, the following 3×4 matrix contains a path for the character string "bfce" (the letters in the path are marked in bold).
[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]
But the matrix does not contain the path of the string "abfb", because after the first character b of the string occupies the second grid in the first row of the matrix, the path cannot enter this grid again.
2. Examples
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D", "E","E"]], word = "ABCCED"
Output: true
Input: board = [["a","b"],["c","d"]], word = "abcd"
Output: false
Two, the solution
1. The time complexity is O(MN)
2. Space complexity O(K)
package com.haoxiansheng.demo01.SwordfingerOffer;
import lombok.extern.slf4j.Slf4j;
/**
* @author flame
* @data 2020/10/25
*/
@Slf4j
public class DFSDemo {
public static void main(String[] args) {
char[][] test = {
{
'a', 'b', 'c', 'e'}, {
's', 'f', 'c', 's'}, {
'a', 'd', 'e', 'e'}};
String word = "bfce";
log.info("DFS=>{}", exist(test, word));
}
public static 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 (dfs(board, words, i, j, 0)) {
return true;
}
}
}
return false;
}
public static boolean dfs(char[][] board, char[] word, int i, int j, int k) {
boolean isIf = i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k];
if (isIf) {
return false;
}
if (k == word.length - 1) {
return true;
}
char tmp = board[i][j];
board[i][j] = '/';
boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i, j - 1, k + 1);
board[i][j] = tmp;
return res;
}
}