华为机试题目
一:题目
/*
* 输入n行m列二进制来描述一副地图,1代表陆地,0代表海水。如果横列或者竖列相连代表它们同属于一块陆地。
* 请实现计算陆地个数的算法,示例如下:
* 输入:
* 5 4
* 1 0 1 0
* 1 1 1 1
* 1 0 0 0
* 0 1 0 1
* 0 0 0 1
* 输出
* 3
* 解决思路:每找到一个岛屿后就把该岛屿变成非岛屿(海水或其他)以免影响对其他岛屿的统计。由于每一块陆地与它相邻的上下左右
* 都有可能会接壤,而接壤后的这块陆地也存在相同的情况,所以应该使用递归来实现,并且递归中因对上下左右来分四步实现。
* 至于递归的返回,由于我们要变统计边清除掉在统计的岛屿,所以我们的递归应该返回消除掉陆地的新的地图。
*/
二:代码
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int sum =0,a = sc.nextInt(),b=sc.nextInt();
int map[][] = new int[a][b];
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
map[i][j] = sc.nextInt();
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
int now = map[i][j];
if(now == 1){
map[i][j] = -1;
map = clean(map,a,b,i,j);
sum++;
}
}
}
System.out.println(sum);
}
}
public static int[][] clean(int[][] map,int a,int b,int i, int j){
if (j-1>=0 && map[i][j-1]==1){//向左边走
map[i][j-1] = -1;
map = clean(map,a,b,i,j-1);
}
if (j+1<b && map[i][j+1]==1){//向右走
map[i][j+1] = -1;
map = clean(map,a,b,i,j+1);
}
if (i-1>=0 && map[i-1][j]==1){//向上边走
map[i-1][j] = -1;
map = clean(map,a,b,i-1,j);
}
if (i+1<a && map[i+1][j]==1){//向下走
map[i+1][j] = -1;
map = clean(map,a,b,i+1,j);
}
return map;
}
}
-----------------------------------------------------------------底线-----------------------------------------------------------------