标签:
题意:给你一个row*col的矩阵表示一块田地,上面的‘W‘代表积水,‘.‘表示干地,问这块田地里面的积水能汇聚成几片水洼
简单的dfs,由于粗心,水和田搞反了,wa了好几次
Memory: 3848K
Time: 1500MS
1 import java.util.Scanner; 2 3 public class Main{ 4 static char map[][]; 5 static int n,m; 6 static boolean visited[][]; 7 static int move[][] = {{0,0,1,-1,1,1,-1,-1},{1,-1,0,0,1,-1,1,-1}}; 8 9 public static boolean isIn(int x,int y){ 10 return x>=0&&x<n&&y>=0&&y<m; 11 } 12 13 public static void dfs(int x,int y){ 14 visited[x][y] = true; 15 for(int i=0;i<8;i++){ 16 int tx = x + move[0][i]; 17 int ty = y + move[1][i]; 18 if(isIn(tx,ty)&&map[tx][ty]!=‘.‘&&visited[tx][ty]==false) 19 dfs(tx,ty); 20 } 21 } 22 23 public static void main(String[] args){ 24 Scanner in = new Scanner(System.in); 25 n = in.nextInt(); 26 m = in.nextInt(); 27 in.nextLine(); 28 map = new char[n][m]; 29 visited = new boolean[n][m]; 30 for(int i=0;i<n;i++){ 31 map[i] = in.nextLine().trim().toCharArray(); 32 } 33 int num=0; 34 for(int i=0;i<n;i++){ 35 for(int j=0;j<m;j++){ 36 if(map[i][j]==‘W‘&&visited[i][j]==false) 37 { 38 dfs(i,j); 39 num++; 40 } 41 } 42 } 43 System.out.print(num); 44 } 45 }
标签:
原文地址:http://www.cnblogs.com/yong-hua/p/4486401.html