poj 1979

题意:给你一个row*col的矩阵,上面的'#'代表你不能走的地方,'.'表示你能走的地方,'@'表示你的起点,问你最多能走多少格。

思路:简单的dfs

Memory: 5036k

Time: 813MS

 

 1 import java.util.Scanner;

 2 

 3 public class Main{

 4     static char map[][];

 5     static boolean visited[][];

 6     static int w,h,sx,sy,sumStep;

 7     static int move[][]={{0,0,1,-1},{1,-1,0,0}};

 8     

 9     public static boolean isIn(int x,int y){

10         return x>=0&&x<h&&y>=0&&y<w;

11     }

12     

13     public static void dfs(int x,int y){

14         sumStep++;

15         visited[x][y] = true;

16         for(int i=0;i<4;i++){

17             int tx = x+move[0][i];

18             int ty = y+move[1][i];

19             if(isIn(tx,ty)&&map[tx][ty]!='#'&&visited[tx][ty]==false){

20                 

21                 dfs(tx,ty);

22             }

23         }

24     return;

25     }

26     

27     public static void main(String[] args){

28         Scanner scan = new Scanner(System.in);

29         while(scan.hasNext()){

30             w = scan.nextInt();

31             h = scan.nextInt();

32             if(w==0&&h==0)

33                 break;

34             scan.nextLine();

35             map = new char[h][w];

36             visited = new boolean[h][w];

37             for(int i=0;i<h;i++){

38                 map[i] = scan.nextLine().toCharArray();

39                 for(int j=0;j<w;j++){

40                     if(map[i][j] == '@'){

41                         sx = i;

42                         sy = j;

43                     }

44                 }

45             }

46             sumStep = 0;

47             dfs(sx,sy);

48             System.out.println(sumStep);

49         }

50     }

51 }

 

你可能感兴趣的:(poj)