#include <iostream>
using namespace std;
char a[20][21];
struct note
{
int x;
int y;
};
int getnum(int, int);
int main()
{
note que[401];
int head, tail;
int book[20][20] = {0};
int i, m, n, startx, starty, max = 0, mx, my, tx, ty, sum;
int next[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
cout << "行数: ";
cin >> n;
cout << "列数: ";
cin >> m;
cout << "起始位置: ";
cin >> startx >> starty;
for(i = 0; i <= n - 1; i++)
{
cin >> a[i];
}
head = 1;
tail = 1;
que[tail].x = startx;
que[tail].y = starty;
tail++;
book[startx][starty] = 1;
max = getnum(startx, starty);
mx = startx;
my = starty;
while(head < tail)
{
for(i = 0; i <= 3; i++)
{
tx = que[head].x + next[i][0];
ty = que[head].y + next[i][1];
if(tx < 0 || tx > n-1 || ty < 0 || ty > m-1)
{
continue;
}
if(a[tx][ty] == '.' && book[tx][ty] == 0)
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
tail++;
sum = getnum(tx, ty);
if(sum > max)
{
max = sum;
mx = tx;
my = ty;
}
}
}
head++;
}
cout << "将炸弹放置在 ( " << mx << " , " << my << " )处,可以实现最多消灭 " << max << "个敌人。" << endl;
system("pause");
return 0;
}
int getnum(int i, int j)
{
int sum, x, y;
sum = 0;
//向上
x = i;
y = j;
while(a[x][y] != '#')
{
if(a[x][y] == 'G')
{
sum++;
x--;
}
}
//向下
x = i;
y = j;
while(a[x][y] != '#')
{
if(a[x][y] == 'G')
{
sum++;
x++;
}
}
//向右
x = i;
y = j;
while(a[x][y] != '#')
{
if(a[x][y] == 'G')
{
sum++;
y++;
}
}
//向左
x = i;
y = j;
while(a[x][y] != '#')
{
if(a[x][y] == 'G')
{
sum++;
y--;
}
}
return sum;
}
输入为:
13 13 3 3
#############
#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#
#############
输入完就像这样,无法输入也不输出结果。