POJ1979 dfs

来源:互联网 发布:visio软件官方下载 编辑:程序博客网 时间:2024/06/06 03:09

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Tile {

static int w;static int h;static int total;static int[] stp = new int[2];static char[][] rect;static int[][] dir={{-1,0},{1,0},{0,-1},{0,1}};public static void main(String[] args) throws FileNotFoundException {    // TODO Auto-generated method stub    Scanner sc = new Scanner(System.in);    sc = new Scanner(new File("src/file/tile"));    while (sc.hasNext()) {        w = sc.nextInt();        h = sc.nextInt();        if(w==0&&h==0)            break;        rect = new char[h + 2][w + 2];        for (int i = 0; i < h + 2; i++) {            rect[i][0] = '#';            rect[i][w + 1] = '#';        }        for (int i = 0; i < w + 2; i++) {            rect[0][i] = '#';            rect[h + 1][i] = '#';        }        for (int i = 1; i < h + 1; i++) {            char[] tmpread = sc.next().toCharArray();            for (int j = 1; j < w + 1; j++) {                rect[i][j] = tmpread[j - 1];                if (tmpread[j - 1] == '@') {                    stp[0] = i;                    stp[1] = j;                }            }        }        total=0;        Walk(stp[0],stp[1]);        System.out.println(total+1);    }}private static void Walk(int x, int y) {    // TODO Auto-generated method stub    for(int i=0;i<4;i++){        int nx=x+dir[i][0];        int ny=y+dir[i][1];        if(rect[nx][ny]=='.'){            rect[nx][ny]='#';            total++;            Walk(nx,ny);        }    }}

}

sample input:
2 2

#

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

@…

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

.

…@…

.

..#.#..
..#.#..
0 0

sample output:
1
45
59
6
13

0 0