Advertisement
Josif_tepe

Untitled

Sep 25th, 2023
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int islandPerimeter(vector<vector<int>>& grid) {
  4.         int n = grid.size();
  5.         int m = grid[0].size();
  6.         int squares = 0;
  7.         int di[] = {0, 0, -1, 1};
  8.         int dj[] = {-1, 1, 0, 0};
  9.         for(int i = 0; i < n; i++) {
  10.             for(int j = 0; j < m; j++) {
  11.                 if(grid[i][j] == 1) {
  12.                     squares += 4;
  13.  
  14.                     for(int k = 0; k < 4; k++) {
  15.                         int ti = i + di[k];
  16.                         int tj = j + dj[k];
  17.                         if(ti >= 0 and ti < n and tj >= 0 and tj < m and grid[ti][tj] == 1) {
  18.                             squares--;
  19.                         }
  20.                     }
  21.                 }
  22.                
  23.             }
  24.         }
  25.         return squares;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement