463. Island Perimeter

這題飛機(jī)上寫(xiě)的。邊界條件蠻多的,以為會(huì)錯(cuò)但竟然一次AC了。
如果我不知道這是一道easy題,應(yīng)該就想不出來(lái)了。。

    public int islandPerimeter(int[][] grid) {
        int res = 0;
        for (int row = 0; row < grid.length; row++)
            for (int col = 0; col < grid[0].length; col++) {
                if (grid[row][col] == 1) {
                    res += calc(row, col, grid);
                }
            }
        return res;
    }

    private int calc(int row, int col, int[][] matrix) {
        int count = 0;
        if (row == 0 || row > 0 && matrix[row - 1][col] == 0) {
            count++;
        }
        if (col == 0 || col > 0 && matrix[row][col - 1] == 0) {
            count++;
        }
        if (row == matrix.length - 1 || row < matrix.length - 1 && matrix[row + 1][col] == 0) {
            count++;
        }
        if (col == matrix[0].length - 1 || col < matrix[0].length - 1 && matrix[row][col + 1] == 0) {
            count++;
        }
        return count;
    }

另外看到一種計(jì)算right neighbor 和 down neighhor最后統(tǒng)一處理的方法:
https://discuss.leetcode.com/topic/68786/clear-and-easy-java-solution

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容