纪念一下本辣鸡在hdu刷的第100道水题,
比较标准的dfs..

Red and Black

Problem Description

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach by repeating the moves described above.

Input

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.

‘.’ – a black tile
‘#’ – a red tile
‘@’ – a man on a black tile(appears exactly once in a data set)

Output

For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).

Sample Input

6 9
….#.
…..#
……
……
……
……
……
#@…#
.#..#.
11 9
.#………
.#.#######.
.#.#…..#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#…….#.
.#########.
………..
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
…@…
###.###
..#.#..
..#.#..
0 0

Sample Output

45
59
6
13

代码实现
import java.util.Scanner;

public class Dfs1312 {
	public static char a[][];
	public static int book[][];
	public static int l;
	public static int h;
	public static int sum;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			l = in.nextInt();
			h = in.nextInt();
			if (h == 0 && l == 0) {
				break;
			}
			a = new char[h][l];
			int startx = 0;
			int starty = 0;
			book = new int[h][l];// 没走的记录为0
			for (int i = 0; i < h; i++) {
				String str = in.next();
				in.nextLine();
				a[i] = str.toCharArray();
				for (int j = 0; j < l; j++) {
					if (a[i][j] == '@') {// 记录出发点
						startx = i;
						starty = j;
					}
				}
			}
			book[startx][starty] = 1;// 标记出发点已走
			sum = 1;
			dfs(startx, starty);
			System.out.println(sum);
		}
	}

	static void dfs(int x, int y) {
		int[][] next = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
		int tx, ty;
		for (int i = 0; i < 4; i++) {// 计算下一点坐标
			tx = x + next[i][0];
			ty = y + next[i][1];
			// 判断是否越界
			if (tx < 0 || tx >= h || ty < 0 || ty >= l) {
				continue;
			}
			if ((a[tx][ty] == '.' || a[tx][ty] == '@') && book[tx][ty] == 0) {// 可以往下走
				book[tx][ty] = 1;// 标记已走
				sum++;
//				 System.out.println(tx+" "+ty);
//				 for(int k=0;k<h;k++){
//					 for(int j=0;j<l;j++){
//						 System.out.print(book[k][j]);
//					 }
//					 System.out.println();
//				 }
				dfs(tx, ty);
			}
		}

	}

}