【发布时间】:2026-01-25 16:20:06
【问题描述】:
#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;
}
}
我不知道我在哪里搞砸了。请帮忙。使用 Here Dfs,移动相邻的 1。 我们知道最多可以有 8 个邻居有 1。所以 Dfs 为 8 次。在这里,我想计算给定二维向量中相邻 1 的最大数量。我无法弄清楚我在哪里弄错了。任何帮助将不胜感激。
【问题讨论】:
-
使用调试器单步调试程序应该有助于识别问题。
-
我没有查看您的代码的详细信息,但您可能想阅读 Why should I not #include <bits/stdc++.h>? 和 Why is “using namespace std;” considered bad practice?。请考虑相应地编辑您的代码和您的问题。
标签: c++ algorithm graph depth-first-search adjacency-matrix