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");
          }
        }
    }
  • 相关阅读:
    PostgreSQL恢复误操作
    PostgreSQL修改表空间
    vim技巧记录
    postgresql recovery.conf文件内容说明
    转一篇pgpool配置
    由PostgreSQL的区域与字符集说起(转)
    PostgreSQL老司机博客 经常翻翻收获不小
    两位数相乘的口算方法
    五线谱升调与降调
    js中的封装、继承、多态
  • 原文地址:https://www.cnblogs.com/z2529827226/p/11634915.html
Copyright © 2011-2022 走看看