杭电acm1312深度优先搜索java程序

import java.util.Scanner;

public class Main {

    public static int result;

    public static void main(String[] args) {
        
        int x = 0;
        int y = 0;
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int[][] arrTiles;
        
            result = 0;
            int ylength = sc.nextInt();
            int xlength = sc.nextInt();
            if(xlength == 0 && ylength==0){
                break;  // 记得退出程序,否则会Wrong Answer
            }
            arrTiles = new int[xlength][ylength];
            for (int i = 0; i < xlength; i++) {
                String lineTxt = sc.next();
                for (int j = 0; j < lineTxt.length(); j++) {
                    if ('@' == lineTxt.charAt(j)) {
                        x = i;
                        y = j;

                        arrTiles[i][j] = 1;
                    } else if ('#' == lineTxt.charAt(j)) {
                        arrTiles[i][j] = 0;
                    } else if ('.' == lineTxt.charAt(j)) {
                        arrTiles[i][j] = 1;
                    }
                }

            }
            search(arrTiles,x, y);
        
            System.out.println(result);
        }

    }

    public static void search(int[][] arrTiles,int x, int y) {
        if (arrTiles[x][y] == -1 || arrTiles[x][y] == 0) {
            return;
        }

        if (arrTiles[x][y] == 1) {
            result += 1;
        }
        arrTiles[x][y] = -1;
        if (x - 1 >= 0) {
            search(arrTiles,x - 1, y);
        }
        if (y + 1 < arrTiles[0].length) {
            search(arrTiles,x, y + 1);
        }
        if (x + 1 < arrTiles.length) {
            search(arrTiles,x + 1, y);
        }
        if (y - 1 >= 0) {
            search(arrTiles,x, y - 1);
        }

    }

}

 

posted @ 2017-07-08 14:47  hzjn1  阅读(153)  评论(0编辑  收藏  举报