唉,每天也就靠看答案解析,来混混日子了。天哪,啥都不会,啥也不是......
推荐作者详解:作者:liweiwei1419
链接:https://leetcode-cn.com/problems/word-search/solution/zai-er-wei-ping-mian-shang-shi-yong-hui-su-fa-pyth/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
个人微改:
class search{
private static final int[][] DIRECTIONS = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
private int rows;
private int cols;
private int len;
private boolean[][] visited;
private char[] charArray;
private char[][] board;
public boolean exist(char[][] board,String word) {
this.rows = board.length;
if(rows==0) return false;
this.cols = board[0].length;
this.visited = new boolean[rows][cols];
this.len = word.length();
this.charArray = word.toCharArray();
this.board = board;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dfs(i, j, 0)) {
return true;
}
}
}
return false;
}
public boolean inArea(int x,int y) {
return x>=0 && x<rows && y>=0 && y<cols;
}
public boolean dfs(int x,int y,int begin) {
if(begin == len-1) {
return board[x][y] == charArray[begin];
}
if(board[x][y] == charArray[begin]) {
visited[x][y] = true;
for(int[] direction:DIRECTIONS) {
int newX = x + direction[0];
int newY = y + direction[1];
if(inArea(newX,newY) && !visited[newX][newY]) {
if(dfs(newX,newY,begin+1)) {
return true;
}
}
}
visited[x][y] = false;
}
return false;
}
}
public class WordSearch {
public static void main(String args[]) {
char[][] board1 = new char[][] {{'A','B','C','D'},{'S','F','C','S'},{'A','D','E','E'}};
String str1 = "ABCCED";
String str2 = "ABCB";
search hah = new search();
System.out.println(hah.exist(board1, str1));
System.out.println(hah.exist(board1, str2));
}
}

本文介绍了一种使用回溯法在二维字符网格中搜索指定单词的方法。通过递归深度优先搜索,遍历网格上每个可能路径,检查是否能构成目标单词。提供了完整的Java实现代码及示例。

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



