一道DFS一道BFS
1979:
DFS无脑扫就可以了
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#define MaxW 20
using namespace std;
int W, H, ans;
char input;
bool sign[MaxW + 10][MaxW + 10];
pair <int, int> start;
bool tra[MaxW + 10][MaxW + 10];
void Tra(int, int);
int main() {
while (scanf("%d%d", &W, &H), !(W == 0 && H == 0)) {
ans = 0;
getchar();
memset(tra, 0, sizeof(tra));
for (int i = 1;i <= H;++ i) {
for (int j = 1;j <= W;++ j) {
scanf("%c", &input);
if(input == '.') sign[i][j] = true;
else if(input == '#') sign[i][j] = false;
else {
sign[i][j] = true;
start = make_pair(i, j);
}
}
getchar();
}
Tra (start.first, start.second);
printf("%d\n", ans);
}
return 0;
}
void Tra(int x, int y) {
//printf ("%d %d\n", x, y);
++ ans;
tra[x][y] = true;
if(x + 1 <= H && sign[x + 1][y] && !tra[x + 1][y])
Tra(x + 1, y);
if(x - 1 >= 1 && sign[x - 1][y] && !tra[x - 1][y])
Tra(x - 1, y);
if(y + 1 <= W && sign[x][y + 1] && !tra[x][y + 1])
Tra(x, y + 1);
if(y - 1 >= 1 && sign[x][y - 1] && !tra[x][y - 1])
Tra(x, y - 1);
}
问题就出在3669上
做法没什么好说的,预处理每个点最早被流星破坏的时间入队前判断一下当前时间是否在最早被流星破坏的时间前就可以了
然后注意题目中给的数据范围是流星坠落的数据范围,并不是整块地的
所以要再开大一点
然后T了3,4次
最后终于发现了问题
在每次入队的时候先把visit给标记了,要不然会多出很多很多相同的冗余元素在队里面,因为bfs和dfs不一样,bfs会一层中一次性入很多元素
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <queue>
#define INF 3000
#define Maxx 300
using namespace std;
struct elem {
int a, b, time;
};
int m, x, y, t, ans;
int destr[Maxx + 10][Maxx + 10];
bool tra[Maxx + 10][Maxx + 10];
int dx[5] = {1, -1, 0, 0, 0};
int dy[5] = {0, 0, 1, -1, 0};
int main() {
ans = -1;
scanf("%d", &m);
for (int i = 0;i < Maxx + 10;++ i)
for (int j = 0;j < Maxx + 10;++ j)
destr[i][j] = INF;
for (int i = 1;i <= m;++ i) {
scanf("%d%d%d", &x, &y, &t);
for (int j = 0;j < 5;++ j)
{
int xx = x + dx[j], yy = y + dy[j];
if(xx >= 0 && yy >= 0)
destr[xx][yy] = min(destr[xx][yy], t);
}
}
if (destr[0][0] == 0) {
printf("-1\n");
return 0;
}
if (destr[0][0] == INF) {
printf("0\n");
return 0;
}
queue <elem> timeline;
elem start; start.a = 0, start.b = 0, start.time = 0;
timeline.push(start);
while(!timeline.empty()) {
elem temp = timeline.front();
timeline.pop();
//tra[temp.a][temp.b] = true;
for(int i = 0;i < 4;++ i) {
int xx = temp.a + dx[i], yy = temp.b + dy[i], tt = temp.time + 1;
if(xx >= 0 && yy >= 0 && destr[xx][yy] > tt && !tra[xx][yy]) {
tra[xx][yy] = true;
if (destr[xx][yy] == INF) {
printf("%d\n", tt);
return 0;
}
start.a = xx;
start.b = yy;
start.time = tt;
timeline.push(start);
}
}
}
printf("-1\n");
return 0;
}