POJ 1979 Red and Black(广搜与深搜两种解答)

题意描述:
一个房间上有红色的瓦和黑色的瓦片,给出红瓦和黑瓦的位置和人所占的位置,求人最多能走过多少片瓦?
(条件为:人行走过程中只能走黑瓦,且人的初始位置为黑瓦)
输入描述:输入的字符里面只有三种字符:
“@”-----表示人(只能有一个该字符)
“.”-----表示黑瓦
“#”-----表示红瓦

样例:
Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.

Sample Output

45

AC代码:
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;

class node{
int x, y;
public node(){
this(0,0);
}
public node(int x,int y){
this.x=x;
this.y=y;
}
}
public class Main{
char room[][];
int w, h;
int dir[][] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int ans;

public Main(int w,int h,char[][] room){
this.w=w;
this.h=h;
this.room=room;
}

public int getAns(){
return ans;
}

public static void main(String args[]){
Scanner in=new Scanner(System.in);
int sx=0;
int sy=0;

while(true){
int w=in.nextInt();
int h=in.nextInt();

if(0 == w && 0 == h)
break;
char room[][]=new char[h][w];
for(int i = 0; i < h; i++){
String s=in.next();
for(int j = 0; j < w; j++){
room[i][j]=s.charAt(j);
if(room[i][j] == '@')
{
sx = i; sy = j;
}
}
}
Main m=new Main(w,h,room);
// System.out.printf("%d\n", m.bfs(sx, sy)); //广搜
m.dfs(sx, sy);
System.out.printf("%d\n", m.getAns());

}
}

private int bfs(int x, int y){
Queue<node> que=new LinkedList<node>();
node t=new node(x,y);
node tmp=new node();

room[x][y] = '#'; //标记为红瓦
que.offer(t);
int nu = 1;
while(!que.isEmpty())
{
tmp = que.poll(); //当前点
for(int i = 0; i < 4; i++){//当前点的所有邻接点
int x1 = tmp.x + dir[i][0];
int y1 = tmp.y + dir[i][1];

if(x1 >= 0 && x1 < h &&y1 >= 0 && y1 < w && room[x1][y1] == '.'){

room[x1][y1] = '#'; //标记为红瓦
que.offer(new node(x1,y1)); //邻接点入队列
nu++;
}
}
}
return nu;
}

private void dfs(int x, int y){
int dx, dy;
if(room[x][y] == '#')
return;
room[x][y] = '#';
ans++;
for(int i = 0; i < 4; i++)
{
dx = x + dir[i][0];
dy = y + dir[i][1];
if(dx >= 0 && dx < h && dy >= 0 && dy < w)
dfs(dx, dy);
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值