2020年9月13日 单词搜索 exist
class Solution {
public boolean exist(char[][] board, String word) {
}
}
解题思路:
首先遍历数组,找到一个对应的起始节点,也就是和word的首字母相同的坐标位置。
然后以这个位置作为起点,对其进行递归处理,这个递归的函数另外写一个,然后返回该点的递归结果。
递归的规则:
当前点是否是字符串的index坐标的字符时,判断index是否是字符串的长度,如果不是,那就判断周围四个是否是目标字符,或者是已经判断过的坐标。
由于字符是不允许重复使用的,那么怎么确定被使用过呢?那就把board复制一个空的出来,在主函数中遍历的时候,找到一个字符相等的就把他清空一遍。这样,在递归过程中就不会出现重复使用,递归结束后清空,这样不会影响下一个递归。
发现错误:进过分析,发现是递归的过程中没有考虑到状态状态的回溯,需要增加一个回溯的功能。
int[][] map;
char[][] board;
int width;
int height;
int len;
String word;
public boolean exist(char[][] board, String word) {
len=word.length();
width=board.length;
height=board[0].length;
this.word=word;
this.board=board;
for (int i=0;i<width;i++){
for (int j=0;j<height;j++){
map=new int[width][height];
if(tryExist(i,j,0))
{
return true;
}
}
}
return false;
}
//递归函数
public boolean tryExist(int x,int y,int index){
if (map[x][y]==1)
return false;
//如果当前位置相等
if (board[x][y]==word.charAt(index)){
//标记位置
map[x][y]=1;
if (index==len-1)
return true;
//递归周围四个
if (x+1<width) {
//如果这一个位置存在,递归他
if (tryExist(x+1,y ,index+1)){
return true;
}
}
if (x-1>-1){
if (tryExist(x-1,y ,index+1)){
return true;
}
}
if (y-1>-1){
if (tryExist(x,y-1 ,index+1)){
return true;
}
}
if (y+1<height){
if (tryExist(x,y+1 ,index+1)){
return true;
}
}
}
return false;
}
二维数组的递归回溯需要复制数组,数组复制有些麻烦。