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 que=new LinkedList();
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);
}

}
}

你可能感兴趣的:(PKU,JudgeOnline,&,HDU)