题:https://leetcode.com/problems/word-search/description/
题目
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.
题目大意
在矩阵中寻找字符串,字符串的相邻字符在矩阵上都相邻 且 矩阵上的字符只能用一次。
思路
组合问题 考虑 BDFS 。
判断问题 作为 递归
递归函数boolean bdfs(board,word,wordLen,curp,r,c ):以r,c为起点 word是否在矩阵中。
递归函数转移方程:bdfs(board,word,wordLen,curp,r,c )= any( bdfs(board,word,wordLen,curp+1,nr,nc )) ,在矩阵当前位置 元素 可作为 word的 当前 字符的情况下,以矩阵当前位置的周围位置为起点 剩余word字串是否在 矩阵中。
终止条件:
- 若word为空,用curp 访问的点为 word 越界表示。返回 true。
- 矩阵当前位置 元素 不 可作为 word的 当前 字符,返回false。
class Solution {
boolean[][] isVisited;
int m,n;
int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}};
public boolean bdfs(char[][] board, String word,int wordLen,int curp,int r,int c){
if(wordLen == curp)
return true;
if(!( r>=0 && r< board.length && c >= 0 && c< board[0].length) || isVisited[r][c] == true || word.charAt(curp) != board[r][c])
return false;
isVisited[r][c] = true;
for(int[] direction:directions) {
int nr = r + direction[0];
int nc = c + direction[1];
if(bdfs(board,word,wordLen,curp+1,nr,nc))
return true;
}
isVisited[r][c] = false;
return false;
}
public boolean exist(char[][] board, String word) {
isVisited = 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(bdfs(board,word,word.length(),0,i,j))
return true;
return false;
}
}