前几天收到了XX工业的面试邀请。公司位于海淀区五道口附近。
属于比较传统的起因。先进行笔试,没有专门面试的屋子,笔试在门口电脑桌上答的。
笔试上面最后一个算法题,计算岛屿个数:
0代表水域 1代表陆地 上下左右相连的陆地周围被水域包围,则该区域为一个岛屿
例如:
{0,0,0,0,0,0,0,0,0,0,1,0},
{0,0,1,0,0,0,0,0,1,0,0,0},
{0,1,1,1,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0}的岛屿个数为4,写出具体的算法。
解题思路
二维数组查找1,查找到后数量+1,并把周围的1都变为0.继续查找。
具体算法:
int[][] arry = {
{0,0,0,0,0,0,0,0,0,0,1,0},
{0,0,1,0,0,0,0,0,1,0,0,0},
{0,1,1,1,1,0,0,0,0,0,0,0},
{0,0,1,0,0,0,0,1,0,0,0,1},
{0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,1},
{0,0,0,0,0,0,0,1,1,0,0,0},
{0,0,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0}
};
int num = calIsLands(arry);//岛屿数量
//循环二维数组,查找岛屿数量
public static int calIsLands(int[][] arry) {
int num =0;
int lenth = arry.length;
for(int i= 0;i
changeIsLands(arry,i,j);
num++;
}
}
}
return num;
}
//递归把周围的1变为0
public static void changeIsLands(int[][] arry,int i,int j) {
if(i<0||j<0||i>=arry.length||j>=arry[i].length||arry[i][j]!=1) {
return;
}
arry[i][j]=0;
changeIsLands(arry,i+1,j);
changeIsLands(arry,i-1,j);
changeIsLands(arry,i,j+1);
changeIsLands(arry,i,j-1);
}