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.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED",
-> returns true,word =
"SEE",
-> returns true,word = "ABCB",
-> returns false.
在一个矩阵里面 找一个单词 也是一个递归问题
public class Solution {
public boolean exist(char[][] board, String word) {
if(word.length()==0)return true;
if(board.length==0||board[0].length==0)return false;
boolean used[][] = 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(helper(board,i,j,0,used,word))return true;
}
}
return false;
}
public boolean helper(char[][]board,int i,int j,int n,boolean[][]used,String word){
if(n==word.length())return true;
if(i<0||j<0||i>=board.length||j>=board[0].length||used[i][j]||board[i][j]!=word.charAt(n))return false;
used[i][j] = true;
boolean res = (helper(board,i+1,j,n+1,used,word)||helper(board,i-1,j,n+1,used,word)||
helper(board,i,j-1,n+1,used,word)||helper(board,i,j+1,n+1,used,word));
used[i][j] = false;
return res;
}
}
本文介绍了一个二维网格中查找特定单词的算法实现。该算法通过递归方式检查网格中是否存在按顺序相邻的字符构成目标单词。文章提供了一个Java实现示例,并详细解释了核心方法`exist`和辅助方法`helper`的具体工作原理。

被折叠的 条评论
为什么被折叠?



