炸弹人 DFS和BFS
炸弹人(DFS与BFS入门)

做出二维数组: # 表示墙壁; G表示敌人 ;. 表示可以安放炸弹的位置;
问题关键:不是所有地点你都可以达到,注意路径问题(比如说(1,11)点是消灭敌人最多的点,但是不一定是炸弹可放置的点);
一、DFS求解
代码如下(示例):
void dfs(int x,int y)
{
int tx,ty,i,j;
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
for(i=0;i<4;i++)
{
tx=x+next[i][0];
ty=y+next[i][1];
if(tx<0 || ty<0 || tx>m-1 || ty>n-1) continue ;
if(a[tx][ty]=='.' && book[tx][ty]==0)
{
book[tx][ty]=1;
max=max>souzhadan(tx,ty)?max:souzhadan(tx,ty);
dfs(tx,ty);
}
}
return;
}
二、BFS
代码如下(示例):
8.14再次更新(c++完整版)
#include <bits/stdc++.h>
using namespace std;
int n, m, book[105][105], ans = 0;
char s[105][105];
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
struct node{
int x, y;
}Node;
int souzhadan(int x, int y){
int i = x, j = y, cnt = 0;
while(i > 0){//上
if(s[i][j] == 'G') cnt++;
else if(s[i][j] == '#')break;
i--;
}
i = x, j = y;
while(i < n - 1){//下
if(s[i][j] == 'G') cnt++;
else if(s[i][j] == '#')break;
i++;
}
i = x, j = y;
while(j > 0){//左
if(s[i][j] == 'G') cnt++;
else if(s[i][j] == '#')break;
j--;
}
i = x, j = y;
while(j < m - 1){//右
if(s[i][j] == 'G') cnt++;
else if(s[i][j] == '#')break;
j++;
}
return cnt;
}
int judge(int x, int y){
if(x >= n || x < 0 || y >= m || y < 0)return 0;
if(book[x][y] == 1 || s[x][y] != '.')return 0;
return 1;
}
void bfs(int x, int y){
queue<node> q;
Node.x = x,Node.y = y;
q.push(Node);
book[x][y] = 1;
ans = souzhadan(x,y);
while(!q.empty()){
node top = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int newX = top.x + next[i][0];
int newY = top.y + next[i][1];
if(judge(newX,newY) == 1){
book[newX][newY] = 1;
ans = max(ans,souzhadan(newX,newY));
Node.x = newX, Node.y = newY;
q.push(Node);
}
}
}
}
/*
13 13
#############
#GG.GGG#GGG.#
###.#G#G#G#G#
#.......#..G#
#G#.###.#G#G#
#GG.GGG.#.GG#
#G#.#G#.#.###
##G...G....##
#G#.#G###.#G#
#...G#GGG.GG#
#G#.#G#G#.#G#
#GG.GGG#G.GG#
#############
3 2
*/
int main() {
int x, y;;
cin >> n >> m;
getchar();
for(int i = 0; i < n; i++){
for(int j = 0; j <= m; j++){
scanf("%c",&s[i][j]);
}
}
cin >> x >> y;
bfs(x,y);
cout << ans << endl;
return 0;
}
# 总结
1 : ==尽可能把所有变量都定义为全局变量,尤其是内存大的数组变量,因为全局变量错太多次了==
2 : ==完成一次遍历搜索千万不要忘记入队 book[ ][ ]=1,BFS入队后往往还有类似操作
Node.x = newX, Node.y = newY;
3 : ==必须学会调试,找到错误的位置,省的一错误 愣住半天,找不到错==

浙公网安备 33010602011771号