洛谷P2845
蓝题搜索,模拟上的细节稍微有点麻烦
#include<iostream>
#include<utility>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
#define fi(i,a,b) for(int i = a; i <= b; ++i)
#define fr(i,a,b) for(int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int,int>;
//#define DEBUG
const int N = 1e4+5;
int n,m;
vector<int> vec[N];
queue<int> que;
int light[N];//表示灯的状态
int connect[N];//表示是否可以连结
int vis[N];//记录是否访问过
int ans;
void bfs(int x){
light[x] = 1;
connect[x] = 1;
ans++;
que.push(x);
while(!que.empty()){
int temp = que.front();
vis[temp] = 1;
que.pop();
if(temp % n != 0 && !connect[temp+1] && light[temp+1]) {
connect[temp+1] = 1;
que.push(temp+1);
}
if(temp % n != 1 && !connect[temp-1] && light[temp-1]){
connect[temp-1] = 1;
que.push(temp-1);
}
if(temp + n <= n * n && !connect[temp + n] && light[temp+n]){
connect[temp+n] = 1;
que.push(temp + n);
}
if(temp - n >= 1 && !connect[temp-n] && light[temp-n]){
connect[temp - n] = 1;
que.push(temp-n);
}
fi(i,0,sz(vec[temp])-1){
int p = vec[temp][i];
if(!light[p]){
light[p] = 1;
ans++;
if(!vis[p] && ((p % n != 0 && connect[p+1])||
(p % n != 1 && connect[p-1])||
(p+n <= n*n && connect[p+n]) || (p-n>=1 && connect[p-n]))){
connect[p] = 1;
que.push(p);
// cout << temp << " " << p << endl;
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
while(m--){
int a,b,c,d;
cin >> a >> b >> c >> d;
int x = (a-1)*n + b;
int y = (c-1)*n + d;
vec[x].pb(y);
}
bfs(1);
cout << ans << endl;
#ifdef DEBUG
//freopen(D:\in.txt,r,stdin);
#endif
return 0;
}