原题网址:https://leetcode.com/problems/word-search/
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 {
private boolean find(char[][] board, boolean[][] used, char[] wa, int pos, int row, int col) {
if (pos == wa.length) return true;
if (row < 0 || row >= board.length || col < 0 || col >= board[row].length) return false;
if (used[row][col]) return false;
if (wa[pos] != board[row][col]) return false;
used[row][col] = true;
if (find(board, used, wa, pos+1, row, col-1)) return true;
if (find(board, used, wa, pos+1, row, col+1)) return true;
if (find(board, used, wa, pos+1, row-1, col)) return true;
if (find(board, used, wa, pos+1, row+1, col)) return true;
used[row][col] = false;
return false;
}
public boolean exist(char[][] board, String word) {
boolean[][] used = new boolean[board.length][board[0].length];
char[] wa = word.toCharArray();
for(int i=0; i<board.length; i++) {
for(int j=0; j<board[i].length; j++) {
if (find(board, used, wa, 0, i, j)) return true;
}
}
return false;
}
}

本文提供了一种使用深度优先搜索解决LeetCode单词搜索问题的方法。通过递归地检查每个可能的方向来查找给定单词是否存在于二维字符网格中。
8600

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



