洛谷 P1141 01迷宫(简单搜索)

题目链接 https://www.luogu.com.cn/problem/P1141

______________________________________________________________________________________________________________________

为了不重复搜索,构建 cnt二维数组,所有搜索时经过的地方都指向最开始的地方。

//简单的搜索
//洛谷  P1141 01迷宫
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
#include <cmath>

#define ll long long
//#define File
#define ull unsigned long long

using namespace std;

const int N=1000+7;
const int M=1000000+7;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;

int n,m,mark,sum=0;       //n ~ 1000 ,  m ~ 100000
string Map[N];
int cnt[N][N];set<int> note;

int dx[]={1,-1,0,0},dy[]={0,0,1,-1};

void dfs(int x,int y,int f)
{
    sum++;
    if(f == 0) cnt[x][y] = mark;
    for(int i=0;i<4;i++){
        int xn = x+dx[i];int yn = y+dy[i];
        if(xn<n && xn>=0 && yn<n && yn>=0 && Map[xn][yn]!=Map[x][y] && cnt[xn][yn] == 0){
            dfs(xn,yn,0);
        }
    }
}

int
main()
{    
    #ifdef File
        //freopen(, , stdin);
        //freopen(, , stdout);
    #endif
    cin>>n>>m;memset(cnt,0,sizeof(cnt));
    for(int i=0;i<n;i++){
        cin>>Map[i];
    }
    int x,y;    //x 行 y 列
    for(int i=0;i<m;i++){
        sum = 0;
        scanf("%d%d",&x,&y);x--;y--;
        mark = N*x+y;
        if(note.count(mark)==1) printf("%d
",cnt[x][y]); 
        else if(cnt[x][y]!=0 && note.count(mark)==0) {
            int tx = cnt[x][y]/N;
            int ty = cnt[x][y]-tx*N;
            printf("%d
",cnt[tx][ty]); 
        }       
        else {
            cnt[x][y]=1;dfs(x,y,1);cnt[x][y] = sum;
            note.insert(mark);
            printf("%d
",sum);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/axchml/p/13721646.html