计算二维数组中的云

时间:2017-06-13 18:42:59

标签: java algorithm data-structures depth-first-search breadth-first-search

我试图从CodeFights中找出这个问题,但我对图遍历没有多少经验,所以我很难挣扎。我读到这个特殊问题的一个提示是“图遍历”,所以我做了一个BFS,但我不知道如何获得云的数量。

出于这个问题和许多其他问题的原因,在为其编写代码时,我的思维往往会变得空白。我试图找到连续的1但是无济于事。有人可以帮帮我吗?

https://codefights.com/interview/pDTvSuHBgAB9dz5ik/companies/N3sScnJbzdPDQaHPj

给定由'1(云)和'0'(晴空)组成的2D网格skyMap,计算云的数量。云被晴朗的天空包围,并通过水平或垂直连接相邻的云形成。您可以假设skyMap的所有四个边都被晴空包围。

实施例

skyMap = [['0', '1', '1', '0', '1'],
         ['0', '1', '1', '1', '1'],
         ['0', '0', '0', '0', '1'],
         ['1', '0', '0', '1', '1']]

输出应该是 countClouds(skyMap)= 2;

skyMap = [['0', '1', '0', '0', '1'],
         ['1', '1', '0', '0', '0'],
         ['0', '0', '1', '0', '1'],
         ['0', '0', '1', '1', '0'],
         ['1', '0', '1', '1', '0']]

输出应该是 countClouds(skyMap)= 5.

1 个答案:

答案 0 :(得分:0)

这是解决问题的粗略方法。你应该尽力改善这一点。

public static void removeCloud(int x, int y, int[][] sky) {
    sky[x][y] = 0;
    if(x > 0 && sky[x-1][y] == 1) {
        removeCloud(x-1,y,sky);
    ...
}

public static int countClouds(int[][] sky) {
    int count = 0
    for(int i = 0; i < sky.length; i++) {
        for(int j = 0; j < sky[i].length) {
            if(sky[i][j] == 1) {
                count++;
                removeCloud(i,j,sky);
            }
        }
    }
}
相关问题