美文网首页
【算法学习】C Island Perimeter

【算法学习】C Island Perimeter

作者: Jiubao | 来源:发表于2017-01-25 15:13 被阅读28次

    题目描述 - leetcode

    You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

    C 解题

    int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {
        int count = 0;
        
        for (int i = 0; i < gridRowSize; i++) {
            for (int j = 0; j < gridColSize; j++) {
                if (grid[i][j] == 1) {
                    count += 4;
                    
                    if ((i < (gridRowSize - 1)) && (grid[i + 1][j] == 1)) {
                        count -= 2;
                    }
                
                    if ((j < (gridColSize - 1)) && (grid[i][j + 1] == 1)) {
                        count -= 2;
                    }
                }
            }
        }
        
        return count;
    }
    

    纠错

    整体思路来说,就是遍历每个位置,找到值是 1 的点,然后查看右侧和下侧是否存在同为 1 的值,如果存在,就需要去边。

    其中遇到过的问题,就是没有做好边界,对 0 的点也进行了右侧及下侧的去边,导致计算出错。

    最后,此计算效率很低。

    相关文章

      网友评论

          本文标题:【算法学习】C Island Perimeter

          本文链接:https://www.haomeiwen.com/subject/bzwtittx.html