提问者:小点点

想要找到一个岛的最大尺寸


#include <bits/stdc++.h> 
using namespace std; 
int ROW,COL;
int isSafe(vector<vector<int>>&M, int row, int col, 
          vector<vector<bool>>&visited) 
{ 
   return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); 
}
int DFS(vector<vector<int>>&M, int row, int col, 
       vector<vector<bool>>&visited ) 
{ 
   int count= 1;
   
   static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; 
   static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
 
   // Mark this cell as visited 
   visited[row][col] = true; 
 
   // Recur for all connected neighbours 
   for (int k = 0; k < 8; ++k) 
       if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)){ 
           count++;
           DFS(M, row + rowNbr[k], col + colNbr[k], visited); 
       }
       return count;
}
int main() 
{ 
   int t;
   cin>>t;
   for(int i=0;i<t;i++){
       int n,m;
       int max = 0;
       cin>>n>>m;
       ROW=n;
       COL=m;
       vector<vector<int>>g(n,vector<int>(m));
        vector<vector<bool>>visited(n,vector<bool>(m));
       for(int i=0;i<n;i++){
           for (int j=0;j<m;j++){
               cin>>g[i][j];
               visited[i][j]=false;
           }
       }

       for(int i = 0; i < n; i ++)
   {
       for(int j = 0; j < m; j++)
       {
           if(!visited[i][j] && g[i][j] == 1)
           {
               
               int c = DFS(g,i,j,visited);
               if(c > max)
               {
                   max = c;
               }
           }
       }
   }
   cout<<max;
   }
}

我不知道我把这事搞砸了。 请帮帮我。 使用此处的Dfs,在1附近行进。 我们知道最多可以有8个邻居有1个。 所以8次Dfs。 这里我要计算给定2D向量中相邻1的最大数目。 我不知道我哪里搞错了。 任何帮助都将不胜感激。


共1个答案

匿名用户

那部分

           count++;
           DFS(M, row + rowNbr[k], col + colNbr[k], visited); 

正在忽略dfs返回的内容。 应该是

           count += DFS(M, row + rowNbr[k], col + colNbr[k], visited); 

相关问题