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,原因是重复搜索超时。

  • 相关阅读:
    CodeForces 7B
    CodeForces 4D
    离散化
    线段树入门
    洛谷 P3951 小凯的疑惑(赛瓦维斯特定理)
    Codeforces 1295D Same GCDs (欧拉函数)
    Codeforces 1295C Obtain The String (二分)
    Codeforces 1295B Infinite Prefixes
    Codeforces 1295A Display The Number(思维)
    Codeforces 1294F Three Paths on a Tree(树的直径,思维)
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/3129521.html
Copyright © 2011-2022 走看看