zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    思考:DFS。若存在多个word,找到一个就可以return了,不然TLE。

    class Solution {
    private:
    	bool visit[100][100];
    	bool flag;
    public:
    	void DFS(bool &flag,vector<vector<char> > board,string word,int i,int j,int dep)
    	{
    		if(flag) return;
    		if(dep==word.size()) {flag=true;return;}
    		visit[i][j]=true;
    		if(j<board[0].size()-1&&board[i][j+1]==word[dep]&&!visit[i][j+1]) DFS(flag,board,word,i,j+1,dep+1);
    		if(i<board.size()-1&&board[i+1][j]==word[dep]&&!visit[i+1][j]) DFS(flag,board,word,i+1,j,dep+1);	
    		if(j>0&&board[i][j-1]==word[dep]&&!visit[i][j-1]) DFS(flag,board,word,i,j-1,dep+1);
    		if(i>0&&board[i-1][j]==word[dep]&&!visit[i-1][j]) DFS(flag,board,word,i-1,j,dep+1);	
    		visit[i][j]=false;
    	}
        bool exist(vector<vector<char> > &board, string word) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		int row=board.size();
    		int line=board[0].size();
    		int i,j;
    		memset(visit,0,sizeof(visit));
    		for(i=0;i<row;i++)
    		{
    			for(j=0;j<line;j++)
    			{
    				flag=false;
    				if(board[i][j]==word[0]) 
    				{
    					DFS(flag,board,word,i,j,1);
    					if(flag) return flag;
    				}
    			}
    		}
    		return flag;
        }
    };
    

      

  • 相关阅读:
    linux centos下载地址
    什么是镜像文件?
    Linux下处理JSON的命令行工具:jq---安装
    CentOS7安装第三方yum源EPEL
    CentOS 6.5 下编译安装 Nginx 1.8.0
    CentOS 6.7 如何启用中文输入法
    Linux Yum 命令使用举例
    YUM 安装及清理
    Linux常用命令之rpm安装命令
    使用git代替FTP部署代码到服务器的例子
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3432146.html
Copyright © 2011-2022 走看看