| 1 | class Solution { |
| 2 | public: |
| 3 | |
| 4 | |
| 5 | void dfs(int i , int j, vector<vector<char>> &arr, vector<vector<int>> &vis){ //function for DFS |
| 6 | |
| 7 | vis[i][j]=1; // mark island as visited |
| 8 | |
| 9 | int dx[]={0,0,1,-1}; // array for changing values of x |
| 10 | int dy[]={-1,1,0,0}; // array for changing values of y |
| 11 | |
| 12 | for(int k=0;k<4;k++){ |
| 13 | if(i+dx[k]<arr.size() && i+dx[k]>=0 && j+dy[k]<arr[0].size() && j+dy[k]>=0 && arr[i+dx[k]][j+dy[k]]=='1' && vis[i+dx[k]][j+dy[k]]==0){ // if index (i+dx,j+dy) is in bounds of the grid, value at that index is 1 and index is not visited, mark it as visited and then perform DFS on it |
| 14 | vis[i+dx[k]][j+dy[k]]=1; |
| 15 | dfs(i+dx[k],j+dy[k],arr,vis); |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | } |
| 20 | |
| 21 | |
| 22 | int numIslands(vector<vector<char>>& grid) { |
| 23 | |
| 24 | if(grid.size()==0){ |
| 25 | return 0; //if grid is empty return 0 |
| 26 | } |
| 27 | if(grid[0].size()==0){ |
| 28 | return 0; //if grid is empty return 0 |
| 29 | } |
| 30 | int count=0; |
| 31 | vector<vector<int>> vis(grid.size(),vector<int>(grid[0].size(),0)); //create an empty grid for denoting which indices have been visited |
| 32 | for(int i=0;i<grid.size();i++){ |
| 33 | for(int j=0;j<grid[0].size();j++){ |
| 34 | if(grid[i][j]=='1' && vis[i][j]==0){ |
| 35 | dfs(i,j,grid,vis); // perform DFS on every cell that is 1 and not visited and increase the count of islands |
| 36 | count++; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | return count; |
| 41 | |
| 42 | } |
| 43 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected