463. Island Perimeter

private int res = 0    
public int allPerimeter(int[][] matrix){
        // sanity check
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == 1){
                    boolean[][] visited  = new boolean[matrix.length][matrix[0].length);
                    
                    dfs(matrix, i, j, visited);
                }
            }
        }
        return res;
    }
}

private void dfs(int[][] matrix, int i, int j, boolean[][] visited){
    int sides = side(matrix, i, j);
    res += sides;
    visited[i][j] = true;
    int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for(int[] dir : dirs){
        int row = i + dir[0];
        int col = j + dir[1];
        // check boundary 
        if(row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length || visited[i][j] || matrix[i][j] == 0) continue;
        dfs(matrix, row, col, res, visited);
    }
}

private int side(int[][] matrix, int i, int j){
    int sides = 4;
    // if boundary and 0 , ++
    int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for(int[] dir : dirs){
int row = i + dir[0];
        int col = j + dir[1];
        // check boundary 
        if(row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length) continue;
        if(matrix[row][col] == 1) sides--;
        }
    }
    return sides;
}

 

loop over the matrix and count the number of islands;
if the current dot is an island, count if it has any right neighbour or down neighbour;
the result is islands
* 4 - neighbours * 2

public class Solution { public int islandPerimeter(int[][] grid) { int islands = 0, neighbours = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { islands++; // count islands if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours } } } return islands * 4 - neighbours * 2; } }

 

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.

 

Example:

Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:


 
 

posted on 2018-09-10 04:49  猪猪&#128055;  阅读(126)  评论(0)    收藏  举报

导航