给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCFD"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "BFDS"
输出:false
package com.loo;
public class SearchWord {
private static final int[] X = new int[] { 1 , 0 , -1 , 0};
private static final int[] Y = new int[] { 0 , 1 , 0 , -1};
public static void main(String[] args) {
char[][] board = new char[][] {
{'A' , 'B' , 'C' , 'E'},
{'S' , 'F' , 'C' , 'S'},
{'A' , 'D' , 'E' , 'E'}
};
String word = "ABCCFD";
String word2 = "SEE";
String word3 = "BFDS";
System.out.println(existsSearchWord(word , board));
}
public static boolean existsSearchWord(String word , char[][] board) {
if (word == null || word.length() == 0 || board == null || board.length == 0) {
return false;
}
boolean[][] visited = new boolean[board.length][board[0].length];
for (int x=0;x<board.length;x++) {
for (int y=0;y<board[0].length;y++) {
if (dfs(word , board , x , y , visited , 0)) {
return true;
}
}
}
return false;
}
public static boolean dfs(String word , char[][] board , int x , int y , boolean[][] visited , int index) {
if (word.charAt(index)!=board[x][y]) {
return false;
} else if (index == word.length()-1) {
return true;
}
boolean result = false;
visited[x][y] = true;
for (int i=0;i<X.length;i++) {
int tx = x + X[i];
int ty = y + Y[i];
if (tx<0 || tx>=board.length || ty<0 || ty >=board[0].length) {
continue;
}
if (!visited[tx][ty]) {
if (dfs(word , board , tx , ty , visited , index+1)) {
result = true;
break;
}
}
}
visited[x][y] = false;
return result;
}
}