halisi7

一个专注技术的组织

0%

炸弹人游戏—bfs

问题描述

image-20220303170407851

image-20220303170427248

image-20220303170448283

代码解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>

char a[21][21];//用来存储地图

struct node {
int x;//横坐标
int y;//纵坐标
};

int getnum(int x,int y) {//
int num=0;//用来计数
int tx, ty;
//从四个方向统计可以消灭的敌人
//向右
tx = x; ty = y;

while (a[tx][ty] != '#') {//判断是不是墙,不是墙继续
if (a[tx][ty] == 'G') {
num++;
}
ty++;
}
//向左
tx = x; ty = y;
while (a[tx][ty] != '#') {
if (a[tx][ty] == 'G') {
num++;
}
ty--;
}
//向上
tx = x; ty = y;
while (a[tx][ty] != '#') {
if (a[tx][ty] == 'G') {
num++;
}
tx++;
}
//向下
tx = x; ty = y;
while (a[tx][ty] != '#') {
if (a[tx][ty] == 'G') {
num++;
}
tx--;
}
return num;
}
int main() {
int i, j, k,n,m,tail,head,max=0,sum=0,tx,ty,mx,my,startx,starty;
struct node que[401];

int book[20][20] = {0};//初始值为0,表示没走过的路径
printf("请输入你要输入几行几列的地图:");
scanf_s("%d %d", &n, &m);
printf("请输入的地图:\n");
for(i=0;i<=n-1;i++)
//for(j=1;j<=m;j++)
scanf_s("%s", a[i],20);//char用%s输入,scanf_s("%s",数组,数组大小)
printf("请输入初始位置:");
scanf_s("%d %d", &startx, &starty);//必须要初始位置

int next[4][2] = { {0,1},{0,-1},{1,0},{1,0} };//四个方向
//队列初始化
tail = 1;
head = 1;
//插入小人的初始坐标
que[tail].x = startx;
que[tail].y = starty;
//初始坐标做标记
book[startx][starty] = 1;
tail++;
max = getnum(startx, starty);
mx = startx;//记录max点x坐标
my = starty;//记录max点y坐标
//队列不为空时循环
while (head < tail) {

for (k = 0; k <= 3; k++) {
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if (tx<1 || tx>n || ty<1 || ty>m)
continue;
if (book[tx][ty] == 0 && a[tx][ty] == '.') {
book[tx][ty] = 1;//标记
//插入新的扩展点
que[tail].x = tx;
que[tail].y = ty;
tail++;
//统计当前拓展点可以消灭的敌人
sum = getnum(tx, ty);
if (sum > max) {//更新max
max = sum;
mx = tx;
my = ty;
}
}

}
head++;
}
printf("将炸弹放置到(%d,%d)处,可以消灭%d个敌人。",mx,my, max);
getchar(); getchar();
return 0;

}

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
请输入你要输入几行几列的地图: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 3
  • ‘#’表示墙 G表示敌人 .表示空地
  • 地图大小规定最大为:20*20

输出

1
将炸弹放置到(711)处,可以消灭10个敌人。

总结:

  • bfs与dfs是解决迷宫问题的算法
  • 必须要初始位置
打赏一下作者~ ฅ( ̳• ◡ • ̳)ฅ