给出一个炸弹超人的地图,以及超人的初始位置,求解讲炸弹放在哪里使得消灭的敌人最多,障碍物表示为#,敌人表示为G,平地表示为“.”,
import java.util.*;
//广度优先遍历
class Node{
int x;
int y;
}
public class Main {
static Scanner in = new Scanner(System.in);
static int[][] bool= new int[50][50];
static char[][] maze= new char[50][50];
static int max=Integer.MIN_VALUE;
static int n,m,px,py;
//方向
static int[][] dir= {
{0,1},//右
{1,0},//下
{0,-1},//左
{-1,0}//上
};
static void bfs( Queue<Node> quen){
int tx=0,ty=0,sum=0;
while(!quen.isEmpty()){
//尝试每一种方向
for (int i = 0; i < 4; i++) {
tx=quen.peek().x+dir[i][0];
ty=quen.peek().y+dir[i][1];
// 判断坐标是否出界
if(tx>n-1||ty>m-1||tx<0||ty<0)
continue;
//如果没在已经走过的路径上并且是平地
if(bool[tx][ty]==0&&maze[tx][ty]=='.'){
bool[tx][ty]=1;
Node e =new Node();
e.x=tx;
e.y=ty;
//把当前节点各个方向能走通的节点入队
quen.add(e);
//统计新纳入的节点的能消灭的敌人个数
sum=getNum(tx, ty);
System.out.println(sum);
//更新最大值
if(sum>max){
max=sum;
px=tx;
py=ty;
}
}
}
//从当前节点开始一步能达的节点已经找到,把它出队,以便下一次从它的下一层开始查找
quen.poll();
}
}
static int getNum(int x,int y){
int sum=0;
int i=x,j=y;
//向上
while(maze[i][j]!='#'){
if(maze[i][j]=='G')
sum++;
i--;
}
i=x;j=y;
//向下
while(maze[i][j]!='#'){
if(maze[i][j]=='G')
sum++;
i++;
}
//向左
while(maze[i][j]!='#'){
if(maze[i][j]=='G')
sum++;
j--;
}
//向右
while(maze[i][j]!='#'){
if(maze[i][j]=='G')
sum++;
j++;
}
return sum;
}
public static void main(String[] args) {
//设置一个队列来保存每个节点
Queue<Node> quen=new LinkedList<Node>();
n=in.nextInt();
m=in.nextInt();
//输入起点终点
int start=in.nextInt();
int end =in.nextInt();
//创建迷宫
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
maze[i][j]=in.next().charAt(0);
bool[i][j]=0;
}
}
Node node=new Node();
node.x=start;
node.y=end;
quen.add(node);
bool[start][end]=1;
max=getNum(start, end);
bfs(quen);
System.out.println(px+" "+py+" "+max);
}
}
测试数据以及结果:
13 13 3 3
# # # # # # # # # # # # #
# G G . G G G # G G G . #
# # # . # G # G # G # G #
# . . . . . . . # . . G #
# G # . # # # . # G # G #
# G G . G G G . # . G G #
# G # . # G # . # . # . #
# # G . . . G . . . . . #
# G # . # G # # # . # G #
# . . . G # G G G . G G #
# G # . # G # G # . # G #
# G G . G G G # G . G G #
# # # # # # # # # # # # #
7 11 10
bfs炸弹超人
最新推荐文章于 2023-09-28 12:18:32 发布