题目链接:https://leetcode.com/problems/word-search/
在二维字符串中要搜索是否存在一条四连通字符序列等于给定字符串,这显然就是深度优先搜索+回溯法的方法。
首先要确定搜索的起点,这个只有暴力方法以每个二维字符数组的元素为起点搜一遍,那么递归的部分应该怎么写?首先要确定每层递归都可能用到的不变的参数,设置相应的全局变量来保存,其次需要一个访问记录的二维数组来标记是否已经取过该位置上的字符(不能重复取)。最关键的就是确定返回条件:当整个字符传都匹配完时意味着存在,当还没有匹配完时,首先不满足数组下标范围的表明当前选择的序列不可能形成目标字符串,然后判断当前字符与目标字符串的特定位置是否相等,如果想等则可以继续深度优先搜索,不等则进行其他方向的选择,四个方向有一个能匹配上就算存在!!!
代码如下:
class Solution {
public static boolean[][] visited;
public static int rows;
public static int cols;
public boolean exist(char[][] board, String word)
{
rows=board.length;
cols=board[0].length;
visited=new boolean[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
if(DFS(0,i,j,board,word))
return true;
}
return false;
}
public static boolean DFS(int idx,int rowIndex,int colIndex,char[][] board,String word)
{
//注意这两个返回条件的顺序
if(idx==word.length())
return true;
if(rowIndex<0 || rowIndex>=rows || colIndex<0 || colIndex>=cols)
return false;
boolean deepin=false;
if(word.charAt(idx)==board[rowIndex][colIndex] && !visited[rowIndex][colIndex])
{
visited[rowIndex][colIndex]=true;
for(int dx=-1;dx<=1;dx++)
{
for(int dy=-1;dy<=1;dy++)
{
if(Math.abs(dx+dy)==1)
deepin=deepin || DFS(idx+1,rowIndex+dx,colIndex+dy,board,word);
}
}
visited[rowIndex][colIndex]=false;
}
return deepin;
}
}