给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入: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
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
和word
仅由大小写英文字母组成
思路:原始思路是四个方向回溯,注意一旦找到word后续不用再进行搜索,立刻停止;但往往面试官会要求做优化,因此优化算法为统计word和board次数,如果一个字母在word中出现了x次,在board中出现了y次,且y<x,则不用再进行查找,直接返回false。
java
StringBuffer buffer=new StringBuffer();
boolean [][]flag=new boolean[6][6];//使用used数组记录哪些已经使用过了,防止重复利用
Map<Character,Integer> map=new HashMap<>();
public boolean exist(char[][] board, String word) {
// 优化:如果一个字母在word中出现了x次,在board中出现了y次,且y<x,则不用再进行查找,直接返回false
for(int m=0;m<word.length();m++){
if(!map.containsKey(word.charAt(m)))
map.put(word.charAt(m),1);
else
map.put(word.charAt(m),map.get(word.charAt(m))+1);
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(map.containsKey(board[i][j]))
map.put(board[i][j],map.get(board[i][j])-1);
}
}
Set<Character> set=new HashSet<>();
for(Character key :set){
if(map.get(key)>0)
return false;
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]==word.charAt(0)){
buffer.append(board[i][j]);
flag[i][j]=true;
if(backTracking(board,word,i,j,1))
return true;
buffer.deleteCharAt(buffer.length()-1);
flag[i][j]=false;
}
}
}
return false;
}
public boolean backTracking(char[][]board,String word,int i,int j,int index){
if(buffer.length()==word.length())
return true;
// 四种情况搜索
if(i+1<board.length&&board[i+1][j]==word.charAt(index)&&flag[i+1][j]==false){
buffer.append(board[i+1][j]);
flag[i+1][j]=true;
if(backTracking(board,word,i+1,j,index+1))
return true;
buffer.deleteCharAt(buffer.length()-1);
flag[i+1][j]=false;
}
if(i-1>=0&&board[i-1][j]==word.charAt(index)&&flag[i-1][j]==false){
buffer.append(board[i-1][j]);
flag[i-1][j]=true;
if(backTracking(board,word,i-1,j,index+1))
return true;
buffer.deleteCharAt(buffer.length()-1);
flag[i-1][j]=false;
}
if(j+1<board[0].length&&board[i][j+1]==word.charAt(index)&&flag[i][j+1]==false){
buffer.append(board[i][j+1]);
flag[i][j+1]=true;
if(backTracking(board,word,i,j+1,index+1))
return true;
buffer.deleteCharAt(buffer.length()-1);
flag[i][j+1]=false;
}
if(j-1>=0&&board[i][j-1]==word.charAt(index)&&flag[i][j-1]==false){
buffer.append(board[i][j-1]);
flag[i][j-1]=true;
if(backTracking(board,word,i,j-1,index+1))
return true;
buffer.deleteCharAt(buffer.length()-1);
flag[i][j-1]=false;
}
return false;
}