- 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.
Subscribe to see which companies asked this question
- 题意:判断word字符串的所有字符是否出现在board中,要求word中相邻字符在board中也必须相邻。
- 解法:回溯法,用个栈来保存访问过的点。
public class Solution {
Stack<Pair> s=new Stack<Pair>();
public boolean exist(char[][] board, String word) {
if(board.length==0 || word.length()==0)
return false;
int row=board.length;
int col=board[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(board[i][j]==word.charAt(0)){
s.push(new Pair(i, j));
if(isExist(board,word,1,i,j))
return true;
s.pop();
}
}
}
return false;
}
public boolean isExist(char[][] board,String word,int index,int i,int j){
int row=board.length;
int col=board[0].length;
if(index>=word.length())
return true;
if(!s.contains(new Pair(i,j+1)) && j+1<col && board[i][j+1]==word.charAt(index)){
s.push(new Pair(i,j+1));
if(!isExist(board,word,index+1,i,j+1)){
s.pop();
}else
return true;
}
if(!s.contains(new Pair(i,j-1)) && j-1>=0 && board[i][j-1]==word.charAt(index)){
s.push(new Pair(i,j-1));
if(!isExist(board,word,index+1,i,j-1)){
s.pop();
}else
return true;
}
if(!s.contains(new Pair(i+1,j)) && i+1<row && board[i+1][j]==word.charAt(index)){
s.push(new Pair(i+1,j));
if(!isExist(board,word,index+1,i+1,j)){
s.pop();
}else
return true;
}
if(!s.contains(new Pair(i-1,j)) && i-1>=0 && board[i-1][j]==word.charAt(index)){
s.push(new Pair(i-1,j));
if(!isExist(board,word,index+1,i-1,j)){
s.pop();
}else
return true;
}
return false;
}
public class Pair{
int x,y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Pair) {
Pair p = (Pair) obj;
if (x==p.x && y==p.y) {
return true;
}
}
return false;
}
}
}