[leetcode 79][单词搜索]
- 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
- 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
示例 2:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
输出:true
class Solution {
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.toCharArray()[0]) {
if (word.length() == 1) {
return true;
}
int[][] index = new int[board.length][board[0].length];
index[i][j] = 1;
if (findRoad(i, j, board,word,0, index)) {
return true;
}
}
}
}
return false;
}
public boolean findRoad(int i, int j, char[][] board, String word, int num, int[][] index) {
num++;
List<String> list = findNext(i,j,board,word.charAt(num), index);
if (list.isEmpty()) {
return false;
}
if (num == word.length() - 1) {
return true;
}
for (String str : list) {
String[] arr = str.split(",");
int[][] newIndex = new int[index.length][index[0].length];
for (int i1 = 0; i1 < board.length; i1++) {
for (int j1 = 0; j1 < board[i1].length; j1++) {
newIndex[i1][j1] = index[i1][j1];
}
}
newIndex[Integer.parseInt(arr[0])][Integer.parseInt(arr[1])] = 1;
if (findRoad(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]), board, word, num, newIndex)) {
return true;
}
}
return false;
}
public List<String> findNext(int i, int j, char[][] board, char target, int[][] index) {
List<String> list = new ArrayList<>();
if (j > 0 && index[i][j - 1] != 1) {
if (board[i][j - 1] == target) {
list.add(String.valueOf(i) +","+ String.valueOf(j - 1));
}
}
if (j < board[0].length - 1 && index[i][j + 1] != 1) {
if (board[i][j + 1] == target) {
list.add(String.valueOf(i) +","+ String.valueOf(j + 1));
}
}
if (i > 0 && index[i - 1][j] != 1) {
if (board[i - 1][j] == target) {
list.add(String.valueOf(i - 1) +","+ String.valueOf(j));
}
}
if (i < board.length - 1 && index[i + 1][j] != 1) {
if (board[i + 1][j] == target) {
list.add(String.valueOf(i + 1) +","+ String.valueOf(j));
}
}
return list;
}
}