基于JAVA代码编译,数据结构Queue+BFS的实现逻辑
public class Island {
//Queue+BFS的实现方式,得到总的岛屿的数量
public static int islands(char[][] point) {
if (point == null || point.length == 0 || point[0].length == 0){
return 0;
}
int row = point.length;// 行
int column = point[0].length;// 列
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (point[i][j] == '1') {
count++;
search(point, i, j);
}
}
}
return count;
}
public static void search(char[][] point,int x,int y){
Queue<TwoTuple> q = new LinkedList();
point[x][y]=2;
q.offer(new TwoTuple(x,y));
while (q.size()!=0){
final TwoTuple poll = q.poll();
final Integer first = poll.first;
final Integer second = poll.second;
point[first][second]=2;
if (first > point.length - 1 && second > point[0].length - 1) {
continue;
}
if (first < point.length - 1 && point[first + 1][second] == '1') {// 向右
q.offer(new TwoTuple(first+1,second));
}
if (y < point[0].length - 1 && point[x][y + 1] == '1') {// 向下
q.offer(new TwoTuple(first,second+1));
}
if (x > 0 && point[x - 1][y] == '1') {// 向左
q.offer(new TwoTuple(first-1,second));
}
if (y > 0 && point[x][y - 1] == '1') {// 向上
q.offer(new TwoTuple(first,second-1));
}
}
}
public static void main(String[] args){
char[][] point = new char[10][10];
int num = 0;
for(int i = 0; i < point.length; i ++){
for(int j = 0; j < point[0].length; j ++){
num = (int)(Math.random()*100);;
if(num >= 80){
point[i][j] = '1';
}else{
point[i][j] = '0';
}
}
}
System.out.println("---------------------------");
for(int i = 0; i < point.length; i ++){
for(int j = 0; j < point[0].length; j ++){
System.out.print(point[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println("岛屿数:" + islands(point));
}
}
class TwoTuple {
public final Integer first;
public final Integer second;
public TwoTuple(Integer a, Integer b){
first = a;
second = b;
}
public String toString(){
return "(" + first + ", " + second + ")";
}
}