zoukankan      html  css  js  c++  java
  • Leetcode word search

    DFS。

    AC的代码

    class Solution {
    public:
    bool flag;
    bool used[250][250];
        bool exist(vector<vector<char> > &board, string word) 
        {
            if(word=="")return true;
            int m=board.size();
            if(m==0)return false;
            int n=board[0].size();
            flag=false;
            for(int i=0;i<m;i++)
            {
                for(int j=0;j<n;j++)
                {
                    used[i][j]=false;
                }
            }
            for(int i=0;i<m;i++)
            {
                for(int j=0;j<n;j++)
                {
                    if(!flag)dfs(0,i,j,board,word);
                }
            }
            return flag;
        }
        void dfs(int depth,int x,int y,vector<vector<char> > &board, string word)
        {
            if(flag)return;
            if(depth==word.size())
            {
                flag=true;
                return;
            }  
            if(x<0||y<0||x>=board.size()||y>=board[0].size())
            return;
            if(used[x][y])return;       
            if(board[x][y]==word[depth])
            {
                  used[x][y]=true;
                  dfs(depth+1,x,y+1,board,word);
                  dfs(depth+1,x+1,y,board,word);
                  dfs(depth+1,x-1,y,board,word);
                  dfs(depth+1,x,y-1,board,word);
                  used[x][y]=false;
            }        
        }
    };
    

     导致部分答案WA的代码:

    void dfs(int depth,int x,int y,vector<vector<char> > &board, string word)
        {
            if(x<0||y<0||x>=board.size()||y>=board[0].size())
            return;
            if(depth==word.size())
            {
                flag=true;
                return;
            }          
            if(used[x][y])return;       
            if(board[x][y]==word[depth])
            {
                  used[x][y]=true;
                  dfs(depth+1,x,y+1,board,word);
                  dfs(depth+1,x+1,y,board,word);
                  dfs(depth+1,x-1,y,board,word);
                  dfs(depth+1,x,y-1,board,word);
                  used[x][y]=false;
            }        
        }
    

     以上代码同样导致judge large时TLE,原因是重复搜索超时。

  • 相关阅读:
    leetcode 之Binary Tree Postorder Traversal
    关于java中this的一些总结
    Javascript的匿名函数与自执行
    js 闭包学习笔记
    滚动条到底自动加载数据
    AMD:异步模块定义
    Sass、LESS 和 Stylus
    【原创】Mysql设置自增长主键的初始值
    -webkit-animation的使用
    CSS滤镜
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/3129521.html
Copyright © 2011-2022 走看看