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;
        }
    };
    

      

  • 相关阅读:
    Zero-shot Relation Classification as Textual Entailment (Abiola Obamuyide, Andreas Vlachos, 2018)阅读笔记:Model
    高阶Erlang:超大只的问答房间
    高阶的Parser:可变运算优先级
    Erlang练习2:火烈鸟
    Erlang实现的模拟kaboose(山寨kahoot)
    Prolog模拟社交圈
    08-bootcss
    07-jQuery
    06-字符串、表单form、input标签
    05-有名/无名函数
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3432146.html
Copyright © 2011-2022 走看看