word = "ABCB", -> returns false.
思路:先找到输入字符串第一个字母的位置(可能有很多个),一个一个遍历这些起始字母节点(一旦找到输入字串则不再继续遍历);以这个点为中心向四个方向上下左右没有被搜寻过的点搜寻,搜寻接下来的字母,当找到下一个则以找到的点为中心,继续上述操作,直到找到字串。
public class Word_Search { public static int count=0; //二维板 public static char board[][]; public static char word[]; //判断该点是否被访问过 public static int judge[][]; //找到搜寻字符串首字母的位置,ArrayList里存放的每个数组是坐标 //首字母的位置可能有很多 public static ArrayList<int[]> Find(char ch) { ArrayList<int[]> al=new ArrayList(); for(int i=0;i<board.length;i++) { for(int j=0;j<board[0].length;j++) { if(board[i][j]==ch) { int position[]=new int[2]; position[0]=i; position[1]=j; al.add(position); } } } return al; } //mark是要搜索的点的下标,x,y是现在所在点的坐标 public static void seek(int findmark,int x,int y,int times) { // System.out.println("times="+times+" findmark="+findmark+" x="+x+" y="+y); //第一个字母已经找到了,所以只要找剩余的就可以了 if(times==word.length-1) { count++; return; } if(x-1>=0) { if(board[x-1][y]==word[findmark]&&judge[x-1][y]==0) { judge[x-1][y]=1; seek(findmark+1,x-1,y,times+1); } } if(x+1<board.length) { if(board[x+1][y]==word[findmark]&&judge[x+1][y]==0) { judge[x+1][y]=1; seek(findmark+1,x+1,y,times+1); } } if(y-1>=0) { if(board[x][y-1]==word[findmark]&&judge[x][y-1]==0) { judge[x][y-1]=1; seek(findmark+1,x,y-1,times+1); } } if(y+1<board[0].length) { if(board[x][y+1]==word[findmark]&&judge[x][y+1]==0) { judge[x][y+1]=1; seek(findmark+1,x,y+1,times+1); } } } public static void solve(String str) { word=str.toCharArray(); //获取字符串开头字母的位置 ArrayList<int[]> al=Find(word[0]); if(al.size()!=0) { //一旦有一个开端点找到了数组则不再继续搜寻 for(int i=0;i<al.size()&&count==0;i++) { //将开端点的判断数组设置为0. judge[al.get(i)[0]][al.get(i)[1]]=1; seek(1,al.get(i)[0],al.get(i)[1],0); //在前一个起点没有找到结果,在进行下一个起始点时要将判断数组清空 for(int k=0;k<judge.length;k++) { for(int j=0;j<judge[0].length;j++) { judge[k][j]=0; } } } if(count>0) { System.out.println("true"); } else { System.out.println("false"); } } else { System.out.println("false"); } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); //输入word String str=sc.next(); //x是行数,y是列数 int x=sc.nextInt(); int y=sc.nextInt(); //初始化判断数组 judge=new int[x][y]; //输入二维板 board=new char[x][y]; for(int i=0;i<x;i++) { for(int j=0;j<y;j++) { //将String转化为Char board[i][j]=sc.next().charAt(0); } } solve(str); } }