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

    思路:

    简单搜索

    总结:

    1. 第一次做的时候忘记加 visited 数组了

    2. 做完 kedebug 的搜索题, 简单搜索问题都变得像小绵羊一样温顺了

    3. 还是 dfs 框架. 书上所写的 dfs 框架, 一般由 DFS, dfs 两个函数拼成, DFS 负责接收参数和变量初始化, dfs 负责一般情况下的遍历. 两个函数连用比仅用一个 dfs 要好的多, 因为减少了很多判断语句. 下面的代码, 相当于 DFS+ dfs.

    代码:

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    const int MAXN = 200;
    bool visited[MAXN][MAXN];
    int dire[4][2] = {-1,0, 1,0, 0,-1, 0,1};
    class Solution {
    public:
    	vector<vector<char> > vec;
    	string str;
    	bool ans;
    
    	void dfs(const int &i, const int &j, const int &depth) {
    		if(depth == str.size()) {
    			ans = true;
    			return;
    		}
    		for(int d = 0; d < 4 && !ans; d ++) {// directions
    			int newi = i+dire[d][0], newj = j+dire[d][1];
    			if(newi >= 0 && newi <vec.size() && newj >= 0 && newj < vec[newi].size() && !visited[newi][newj]) {
    				if(vec[newi][newj] == str[depth]) {
    					visited[newi][newj] = 1;
    					dfs(newi, newj, depth+1);
    					visited[newi][newj] = 0;
    				}
    			}
    		}
    	}
        bool exist(vector<vector<char> > &board, string word) {
            vec = board;
    		str = word;
            ans = false;
    		memset(visited, 0, sizeof(visited));
    		for(int i = 0; i < board.size()&&!ans; i ++) {
    			for(int j = 0; j < board[i].size()&&!ans; j++) {
    				if(board[i][j] == word[0]) {
    					visited[i][j] = true;
    					dfs(i, j, 1);
    					visited[i][j] = false;
    				}
    			}
    		}
    		return ans;
        }
    };
    

      

  • 相关阅读:
    [NOI2012] 美食节
    [NOI2008] 志愿者招募
    P3834 【模板】可持久化线段树 2(主席树)
    P3919 【模板】可持久化线段树 1(可持久化数组)
    P4168 [Violet]蒲公英
    轻重链剖分
    沉舟侧畔千帆过 病树前头万木春
    P2119 魔法阵 (0.1s 虐杀过程)
    两行虐杀儒略历
    CSP2020 S-2 爆零(日)记 (已完结)
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3439529.html
Copyright © 2011-2022 走看看