zoukankan      html  css  js  c++  java
  • Java版单词搜索

    package bfs;
    
    class Solution{
        private boolean used[][];
        private int dir[][]=new int[][] {{-1,0},{0,-1},{1,0},{0,1}};
        public boolean isCheckMove(String[] map,int x,int y) {
            return x>=0&&x<map.length&&y>=0&&y<map[x].length();
        }
         public boolean bfs(String[] map,String word,int Index,int startX,int startY) {
             if(word.charAt(Index)==map[startX].charAt(startY)) {
                 if(Index==word.length()-1) {
                     return word.charAt(Index)==map[startX].charAt(startY);
                 }
                 used[startX][startY]=true;
                 for(int i=0;i<4;++i) {
                     int newX=startX+dir[i][0];
                     int newY=startY+dir[i][1];
                     if(isCheckMove(map,newX,newY)&&!used[newX][newY]&&bfs(map,word,Index+1,newX,newY)) {
                         return true;
                     }
                 }
                 used[startX][startY]=false;
             }
             return false;
         }
         public boolean num(String[] map,String word) {
             used=new boolean[map.length][map[0].length()];
             for(int i=0;i<map.length;++i) {
                 for(int j=0;j<map[i].length();++j) {
                     used[i][j]=false;
                 }
             }
            for(int i=0;i<map.length;++i) {
                for(int j=0;j<map[i].length();++j) {
                    if(word.charAt(0)==map[i].charAt(j)&&bfs(map,word,0,i,j)) {
                        return true;
                    }
                }
            }
             return false;
         }
    }
    
    
    public class Test {
        public static void main(String[] args) {
          String word="bfskhj";
          String map[]= {"abc","dfe","fsg","hkj"};
          Solution space=new Solution();
          if(space.num(map, word)) {
              System.out.println("true");
          }
          else {
              System.out.println("false");
          }
        }
    }
  • 相关阅读:
    优秀大整数
    洛谷—— P3908 异或之和
    洛谷—— P1869 愚蠢的组合数
    洛谷—— P1680 奇怪的分组
    洛谷—— P1609 最小回文数
    Something I like
    数学相关
    新博客测试中~
    P3369 【模板】普通平衡树
    2017 11.6 NOIP模拟赛
  • 原文地址:https://www.cnblogs.com/z2529827226/p/11634915.html
Copyright © 2011-2022 走看看