zoukankan      html  css  js  c++  java
  • [leedcode 79] 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"]
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    public class Solution {
        public boolean exist(char[][] board, String word) {
            //这道题很容易感觉出来是图的题目,其实本质上还是做深度优先搜索(DFS和递归)。
            //基本思路就是从某一个元素出发,往上下左右深度搜索是否有相等于word的字符串。
            //这里注意每次从一个元素出发时要重置访问标记(也就是说虽然单次搜索字符不能重复使用,
            //但是每次从一个新的元素出发,字符还是重新可以用的)。我们知道一次搜索的复杂度是O(E+V),E是边的数量,V是顶点数量,在这个问题中他们都         //是O(m*n)量级的(因为一个顶点有固定上下左右四条边)。加上我们对每个顶点都要做一次搜索
            //,所以总的时间复杂度最坏是O(m^2*n^2),空间上就是要用一个数组来记录访问情况,所以是O(m*n)
            boolean[][] flag=new boolean[board.length][board[0].length];
            for(int i=0;i<board.length;i++){
                for(int j=0;j<board[0].length;j++){
                    if(isExist(board,word,0,i,j,flag))
                        return true;//注意开始的搜索
                }
            }
            return false;
        }
        public boolean isExist(char[][] board,String word,int level,int i,int j,boolean[][] flag){
            if(level==word.length())
                return true;
             if(i>=board.length||i<0||j>=board[0].length||j<0||flag[i][j]) return false; 
             boolean temp=false;
             if(flag[i][j]==false&&board[i][j]==word.charAt(level)){
                 flag[i][j]=true;
                 temp= isExist(board,word,level+1,i+1,j,flag)||isExist(board,word,level+1,i-1,j,flag)||
                 isExist(board,word,level+1,i,j+1,flag)||isExist(board,word,level+1,i,j-1,flag);
                 flag[i][j]=false;/////////
             }
             return temp;
        }
    }
  • 相关阅读:
    [iOS基础控件
    [iOS基础控件
    后端程序员必会常用Linux命令总结
    MySQL数据库SQL语句基本操作
    MySQL拓展操作
    http/1.0/1.1/2.0与https的比较
    http中的socket是怎么一回事
    Django content_type 简介及其应用
    WEB主流框架技术(汇聚页)
    WEB基础技术(汇聚页)
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4646788.html
Copyright © 2011-2022 走看看