Number of Distinct Islands in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary 2D array grid, here an island is a group of 1's (land) connected 4- directionally (horizontal or vertical.) We can assume all four edges of the grid are surrounded by water. We have to count the number of distinct islands.

An island is considered to be the same as another when one island can be translated (and not rotated or reflected) to equal the other.

So, if the input is like

11011
10000
00001
11011

then the output will be 3

To solve this, we will follow these steps −

  • Define a function dfs(), this will take x, y, grid, temp, c,

  • if x and y not in inside the grid rows and columns and grid[x,y] is 0, then −

    • return

  • grid[x, y] := 0

  • temp := temp concatenate c

  • dfs(x + 1, y, grid, temp, 'r')

  • dfs(x - 1, y, grid, temp, 'l')

  • dfs(x, y + 1, grid, temp, 'd')

  • dfs(x, y - 1, grid, temp, 'u')

  • temp := temp concatenate 'b'

  • From the main method do the following −

  • ret := 0

  • Define one set visited

  • for initialize i := 0, when i < row count of grid, update (increase i by 1), do −

    • for initialize j := 0, when j < col count of grid, update (increase j by 1), do −

      • if grid[i, j] is non-zero, then −

        • aux := empty string

        • dfs(i, j, grid, aux, 's')

        • if aux is not in visited, then −

          • (increase ret by 1)

          • insert aux into visited

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
class Solution {
public:
   void dfs(int x, int y, vector < vector <int> >& grid, string& temp, char c){
      if (x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || !grid[x][y])
         return;
      grid[x][y] = 0;
      temp += c;
      dfs(x + 1, y, grid, temp, 'r');
      dfs(x - 1, y, grid, temp, 'l');
      dfs(x, y + 1, grid, temp, 'd');
      dfs(x, y - 1, grid, temp, 'u');
      temp += 'b';
   }
   int numDistinctIslands(vector<vector<int>>& grid) {
      int ret = 0;
      set<string> visited;
      for (int i = 0; i < grid.size(); i++) {
         for (int j = 0; j < grid[0].size(); j++) {
            if (grid[i][j]) {
               string aux = "";
               dfs(i, j, grid, aux, 's');
               if (!visited.count(aux)) {
                  ret++;
                  visited.insert(aux);
               }
            }
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v =
   {{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}};
   cout<<(ob.numDistinctIslands(v));
}

Input

{{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}}

Output

3
raja
Published on 17-Nov-2020 10:34:21
Advertisements