Advertisement
1988coder

463. Island Perimeter

Jan 1st, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. /**
  2.  * Refer:
  3.  * https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution
  4.  *
  5.  * Loop over the matrix and count the number of islands. If the current dot is
  6.  * an island, count if it has any right neighbour or down neighbour. The result
  7.  * is islands*4 - neighbours*2.
  8.  *
  9.  * Time Complexity: O(M * N)
  10.  *
  11.  * Space Complexity: O(1)
  12.  *
  13.  * M = Number of rows in the grid. N = Number of columns in the grid.
  14.  */
  15. class Solution {
  16.     public int islandPerimeter(int[][] grid) {
  17.         if (grid == null || grid.length == 0 || grid[0].length == 0) {
  18.             return 0;
  19.         }
  20.  
  21.         int islands = 0;
  22.         int neighbours = 0;
  23.         int rows = grid.length;
  24.         int cols = grid[0].length;
  25.  
  26.         for (int i = 0; i < rows; i++) {
  27.             for (int j = 0; j < cols; j++) {
  28.                 if (grid[i][j] == 1) {
  29.                     islands++;
  30.                     if (j < cols - 1 && grid[i][j + 1] == 1) {
  31.                         neighbours++;
  32.                     }
  33.                     if (i < rows - 1 && grid[i + 1][j] == 1) {
  34.                         neighbours++;
  35.                     }
  36.                 }
  37.             }
  38.         }
  39.  
  40.         return islands * 4 - neighbours * 2;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement