Skip to content

Instantly share code, notes, and snippets.

@pratt3000
Last active August 28, 2023 23:51
Show Gist options
  • Save pratt3000/cf4ac16258d878424d082b76dbc91631 to your computer and use it in GitHub Desktop.
Save pratt3000/cf4ac16258d878424d082b76dbc91631 to your computer and use it in GitHub Desktop.
UNO.ai: Islands - m x n 2D binary grid
#include<bits/stdc++.h>
using namespace std;
// Initialize helper data structures and visited array.
vector<int> x{-1, 1, 0, 0};
vector<int> y{0, 0, -1, 1};
int visited[1000][1000] = {0};
// If its a visited node, then ignore.
// If the element is 0 then ignore as there is no island on that path, i.e. the coast.
int isvalid(int i, int j, vector<vector<char>>& grid){
if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size()) return 0;
if(visited[i][j] == 1) return 0;
if(grid[i][j] == '0') return 0;
// return 1 if its a valud land piece
return 1;
}
int dfs(int i, int j, vector<vector<char>>& grid){
// Ignore if visited, if not then visit it.
if(visited[i][j] == 1) return 0;
visited[i][j] = 1;
// Check in all 4 directions of the current land piece.
for(int k=0; k<4; k++){
int valid = isvalid(i+x[k],j + y[k], grid);
if (valid == 0) continue;
int a = dfs(i+x[k], j+ y[k], grid);
}
return 0;
}
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
// Iterate all land pieces and call function for all those that are not visited and actually land.
int ans = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '1' && visited[i][j] == 0) {
int is_island = dfs(i, j, grid);
ans += 1;
}
}
}
return ans;
}
// Take inputs from the user, process and display output.
int main(){
vector<vector<char>> islands;
cout<<"\nEnter size of islands in m, n:\n";
int m, n;
cin>>m>>n;
cout<<"\nEnter the terrain info in 1, 0 fashion in an mxn grid: \n";
for(int i=0; i<m; i++){
vector<char> temp;
for(int j=0; j<n; j++){
int x; cin>>x;
if(x==0) temp.push_back('0');
else temp.push_back('1');
}
islands.push_back(temp);
}
int ans = numIslands(islands);
cout<<"\nNumber of islands = "<<ans;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment