Word_Search

来源:互联网 发布:有哪些搜索算法 编辑:程序博客网 时间:2024/05/21 18:47
题目描述: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 =
                 [
                  ["ABCE"],
                  ["SFCS"],
                  ["ADEE"]
                 ]
                 word = "ABCCED", -> returns true,
                 word = "SEE", -> returns true,

                 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);//输入wordString 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转化为Charboard[i][j]=sc.next().charAt(0);}}solve(str);}}


原创粉丝点击