FreeEvil767 @ 2024-01-31 19:15:43
为啥这一段过不了啊?(#3,#5-10 TE)
#include <bits/stdc++.h>
using namespace std;
int n,dx[5]={0,1,-1,0,0},dy[5]={0,0,0,1,-1};
bool vst[1009][1009],l[1009][1009];
char c[1009][1009];
struct node{
int x,y;
};
queue<node> q;
bool vaild(int x,int y){
return 1<=x&&x<=n&&1<=y&&y<=n;
}
int bfs(){
int cnt=0;
for (int i=1;i<=n;++i){
for (int j=1;j<=n;++j){
if (c[i][j]=='#'&&(!vst[i][j])){
bool flag=false;
q.push((node){i,j});
while (!q.empty()){
node u=q.front();q.pop();
int x=u.x,y=u.y;vst[x][y]=1;
if (l[x][y]) flag=true;
for (int k=1;k<=4;++k){
int prex=x+dx[k],prey=y+dy[k];
if (vaild(prex,prey)&&(!vst[prex][prey])&&(c[prex][prey]=='#')) q.push((node){prex,prey});
}
}
if (!flag) ++cnt;
// cout<<i<<" "<<j<<" "<<flag<<endl;
}
}
}
return cnt;
}
int main(){
cin>>n;for (int i=1;i<=n;++i) for (int j=1;j<=n;++j) cin>>c[i][j];
for (int i=1;i<=n;++i){
for (int j=1;j<=n;++j){
int x=i,y=j;
l[x][y]=(c[i][j]=='#');
if (c[x][y]=='#'){
for (int k=1;k<=4;++k){
int prex=x+dx[k],prey=y+dy[k];
if (!(vaild(prex,prey))) continue;
if (c[prex][prey]=='.') l[x][y]=0;
}
}
//cout<<l[x][y];
}
//cout<<endl;
}
cout<<bfs()<<endl;
return 0;
}
by gaojizhe05 @ 2024-01-31 19:21:57
@Dark_forest728 BFS用于最短路径,DFS用于判断连通性,两个搜索的侧重点不一样,混用容易TLE
by FreeEvil767 @ 2024-01-31 19:26:10
上面就是一个纯bfs程序啊,为什么会TLE呢? @gaojizhe05
by Bingxiu @ 2024-01-31 19:28:48
@Dark_forest728 刘SY好强!!!
说说看,为啥 if (vaild(prex,prey)&&(!vst[prex][prey])&&(c[prex][prey]=='#')) q.push((node){prex,prey});
没有设置 vst
,而是 int x=u.x,y=u.y;vst[x][y]=1;
里设置了 vst
?
给一个图你就懂了
##.......
###......
.###.....
..###....
...###...
....###..
.....###.
......###
.......##
这个图里,
by Bingxiu @ 2024-01-31 19:30:35
@gaojizhe05 这又是哪来的邪教说法,谁说 BFS 用于最短路的,递归栈爆的时候或者有访问次序的时候都是 BFS 吧
by FreeEvil767 @ 2024-01-31 19:33:23
@Bingxiu 谢,刚我做P1135的时候自己发现了……
by gaojizhe05 @ 2024-01-31 19:35:06
@Bingxiu 我只是说本题
by Bingxiu @ 2024-01-31 19:35:23
@Dark_forest728 刘
by gaojizhe05 @ 2024-01-31 19:35:50
@Bingxiu 类似01迷宫的板子题
by Bingxiu @ 2024-01-31 19:35:54
@gaojizhe05 啊?你仔细看看他的代码在说话行不行
by Bingxiu @ 2024-01-31 19:36:18
@gaojizhe05 啊?什么东东?这题咋就变成迷宫了?