Rocket_striker's blog

By Rocket_striker, history, 7 years ago, In English

Here is the question

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.

Example 2:

Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation:

All 1s are either on the boundary or can reach the boundary.

My CODE

  • class Solution {
  • public:
  • int vis[1000][1000];
  • void dfs(int x,int y,int n,int m,vector<vector > &a,int &c,int &flag)
  • {
  • if(x<0 || y<0 || x>=n || y>=m || a[x][y]==0 || vis[x][y]==1)
  • return ;
  • c++;
  • if(x==0 || x==n-1 || y==0 ||y==m-1)
  • flag=1;
  • dfs(x+1,y,n,m,a,c,flag);
  • dfs(x-1,y,n,m,a,c,flag);
  • dfs(x,y+1,n,m,a,c,flag);
  • dfs(x,y-1,n,m,a,c,flag);
  • }
  • int numEnclaves(vector<vector>& a) {
  • int n=a.size(),m=a[0].size();
  • int i,j;
  • int ans=0;
  • memset(vis,0,sizeof(vis));
  • for(i=0;i<n;i++)
  • {
  • for(j=0;j<m;j++)
  • {
  • if(vis[i][j]==0 && a[i][j]==1)
  • {
  • int c=0;
  • int flag=0;
  • dfs(i,j,n,m,a,c,flag);
  • if(flag==1)
  • ans+=c;
  • }
  • }
  • }
  • return ans;
  • }
  • };

ERROR: Runtime Error Message: AddressSanitizer: stack-overflow on address 0x7ffffafe0ff8 (pc 0x0000003833d7 bp 0x7ffffafe10c0 sp 0x7ffffafe1000 T0)

Thank you...

Full text and comments »

  • Vote: I like it
  • -4
  • Vote: I do not like it