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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word = "ABCB"
, -> returns false
.
Source
public class Solution {
public boolean exist(char[][] board, String word) {
if(word.length() == 0) return false;
boolean[][] map = new boolean[board.length][board[0].length]; //注意维度值
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
map[i][j] = false;
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(word.charAt(0) == board[i][j]){
map[i][j] = true;
if(word.length() == 1 || visit(i, j, word.substring(1), map, board)) //toString(i) 截取从i到末尾的String值
return true;
}
map[i][j] = false;
}
}
return false;
}
public boolean visit(int i, int j, String word, boolean[][] map, char[][] board){
if(word.length() == 0) return true;
if((i - 1) >= 0 && map[i - 1][j] == false && word.charAt(0) == board[i - 1][j]){
map[i - 1][j] = true;
if(word.length() == 1 || visit(i - 1, j, word.substring(1), map, board)) return true;
map[i - 1][j] = false; //***
}
if((j - 1) >= 0 && map[i][j - 1] == false && word.charAt(0) == board[i][j - 1]){
map[i][j - 1] = true;
if(word.length() == 1 || visit(i, j - 1, word.substring(1), map, board)) return true;
map[i][j - 1] = false; //***
}
if((j + 1) < board[0].length && map[i][j + 1] == false && word.charAt(0) == board[i][j + 1]){
map[i][j + 1] = true;
if(word.length() == 1 || visit(i, j + 1, word.substring(1), map, board)) return true;
map[i][j + 1] = false; //***
}
if((i + 1) < board.length && map[i + 1][j] == false && word.charAt(0) == board[i + 1][j]){
map[i + 1][j] = true;
if(word.length() == 1 || visit(i + 1, j, word.substring(1), map, board)) return true;
map[i + 1][j] = false; //***
}
return false;
}
}
- int[][] direction = { {-1,0},{1,0},{0,-1},{0,1}};
- for (int k=0;k<direction.length;k++) {
- int ii = i + direction[k][0];
- int jj = j + direction[k][1];
- if ( ii>=0&&ii<board.length&&
- jj>=0&&jj<board[i].length&&
- board[ii][jj]==word.charAt(0)&&
- visited[ii][jj]==false) {
Test
public static void main(String[] args){
char[][] board = {{'a','a','a','a'},{'a','a','a','a'},{'a','a','a','a'}};
String word = "aaaaaaaaaaaaa";
System.out.println(new Solution().exist(board, word));
}