岛屿数量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qfashly/article/details/79548308

今晚看到群里有人发了一个面试题,看看挺有意思的,所有吧算法写下来。
题目是:
给定 1(代表陆地)和 0(代表水)的2d网格图,计算岛的数量。 一个岛屿被水包围,并且通过水平或垂直方式连接相邻的陆地而形成。你可以假设网格的所有四个边缘都在水边,统计岛的数量,如下图:

Example 1:
11110
11010
11000
00000
答案: 1

Example 2:
11000
11000
00100
00011
答案: 3
思路:广度优先搜索(https://www.cnblogs.com/0kk470/p/7555033.html)。遍历到point(i,j)时,如果point(i,j)为1,则count ++,同时标记point(i,j)为已经遍历的point,接下来遍历point(i,j)的上下左右四个点,从这四个点递归遍历,是1标记为已经遍历的点,是0停止遍历。
转载请注明:https://mp.csdn.net/mdeditor/79548308

    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) {
        point[x][y] = '2';//标记为已经遍历的点
        if (x > point.length - 1 && y > point[0].length - 1) {
            return;
        }
        if (x < point.length - 1 && point[x + 1][y] == '1') {// 向右
            search(point, x + 1, y);
        }
        if (y < point[0].length - 1 && point[x][y + 1] == '1') {// 向下
            search(point, x, y + 1);
        }
        if (x > 0 && point[x - 1][y] == '1') {// 向左
            search(point, x - 1, y);
        }
        if (y > 0 && point[x][y - 1] == '1') {// 向上
            search(point, x, y - 1);
        }
    }
    public static void main(String[] args){
        char[][] point = new char[10][20];
        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));
    }

00000001011000100000
00000110000011000000
00011010101100100010
00001010100000010000
01001000010000000101
00001001000000000001
01000000000000000000
10000010000000000000
00000000001000000000
00000101100000110001


岛屿数:24

猜你喜欢

转载自blog.csdn.net/qfashly/article/details/79548308
今日推荐