zoukankan      html  css  js  c++  java
  • Word Search

    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"]
    ]
    解题思路: 类似于迷宫,递归回溯。需要一个辅助数组记录走过的位置,防止同一个位置被使用多次。
    public class Solution {
        public boolean exist(char[][] board, String word) {
            if(word==null){
                return true;
            }
            boolean bool[][]=new boolean[board.length][board[0].length];
            for(int i=0;i<board.length;i++){
                for(int j=0;j<board[i].length;j++){
                    bool[i][j]=false;
                }
            }
             for(int i=0;i<board.length;i++){
                for(int j=0;j<board[i].length;j++){
                    if(board[i][j]==word.charAt(0)){
                        bool[i][j]=true;
                      if(search(board,word.substring(1),i,j,bool))//注意:当search返回false时,还要继续遍历,记得把bool置为false
                        return true;
                      else
                        bool[i][j]=false;
                    }
                    
                }
            }
            return false;
            
        }
        boolean search(char[][] board,String word,int i,int j,boolean[][]bool){
            if(word.length()==0) return true;//判断条件根据length,不是null
            int [][]director={{-1,0},{1,0},{0,-1},{0,1}};//此处非常有技巧,代表四个方向
            for(int k=0;k<director.length;k++){
                int ii=i+director[k][0];
                int jj=j+director[k][1];
                if(ii>=0&&ii<board.length&&jj>=0&&jj<board[0].length){
                     if(board[ii][jj]==word.charAt(0)&&bool[ii][jj]==false){
                        bool[ii][jj]=true;
                     if(search(board,word.substring(1),ii,jj,bool))
                        return true;
                     else 
                        bool[ii][jj]=false;
                }
                    
                }
               
            }
            return false;
            
            
            
        }
    }
  • 相关阅读:
    关闭弹出窗体,刷新父页面
    Oracle 导出部分表结构,以及导入
    ORCLE报错解决(ora01747:无效的用户.表.列,表.列)
    PL/SQL Developer使用技巧
    自定义table
    Array查询数组中是否包含指定字符
    水晶报表去掉多余小数点
    HttpHandler HttpModule入门篇
    窗口类名无效 错误 解决方法
    2020.10.15
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4396488.html
Copyright © 2011-2022 走看看