题目:
第一行输入一个整数a,表示共有a组数据
每一组数据都是先输入行数row 与 列数col
然后,输入接下来的row行col列个数据表示此处是否有水(1表示是水,0表示是地面)
分析:
1 2 3 4 5 6 7 8
| 先找到一个,然后在判断它的上下左右,有挨着的表示同一个水坑 例如:(5行4列)共有3个小水坑 5 4 1 1 1 0 0 0 1 0 1 0 1 0 1 0 0 1 1 0 1 1
|
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class pool { static int[][] pools; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入a组测试数据:"); int a = sc.nextByte(); for (int i = 0; i < a; i++) { System.out.println("输入m行n列:"); int row = sc.nextByte(); int col = sc.nextByte(); pools = new int[row][col]; for (int j = 0; j < row; j++) { for (int j2 = 0; j2 < col; j2++) { pools[j][j2] = sc.nextByte(); } } int count=0; for (int j = 0; j < row; j++) { for (int j2 = 0; j2 < col; j2++) { if (pools[j][j2]==1) { count++; judge(j,j2); }else continue; } } System.out.println(count); } }
private static void judge(int j,int j2) { if(pools[j][j2]==0) return; pools[j][j2]=0; if(j>0) judge(j-1,j2); if(j<pools.length-1) judge(j+1,j2); if(j2>0) judge(j,j2-1); if(j2<pools[j].length-1) judge(j,j2+1); } }
|