Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Refer:
- * https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution
- *
- * 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.
- *
- * Time Complexity: O(M * N)
- *
- * Space Complexity: O(1)
- *
- * M = Number of rows in the grid. N = Number of columns in the grid.
- */
- class Solution {
- public int islandPerimeter(int[][] grid) {
- if (grid == null || grid.length == 0 || grid[0].length == 0) {
- return 0;
- }
- int islands = 0;
- int neighbours = 0;
- int rows = grid.length;
- int cols = grid[0].length;
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- if (grid[i][j] == 1) {
- islands++;
- if (j < cols - 1 && grid[i][j + 1] == 1) {
- neighbours++;
- }
- if (i < rows - 1 && grid[i + 1][j] == 1) {
- neighbours++;
- }
- }
- }
- }
- return islands * 4 - neighbours * 2;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement