I'm solving a programming problem with dfs. The tldr is as follows: There are n cows at coordinates x, y. They can communicate to others within their radius of "voicability" p. Just because cow a can communicate to cow b, doesn't mean b can communicate back if it doesn't have sufficient p. If a message starts at any cow, what is the greatest number of cows it will be able to reach? Cows can relay messages from one to another. Ex. If b can hear a, and c cannot hear a but can hear b, b can relay info from a to c, so 3 cows hear the info in this case. Here is a sample input:
4
1 3 5
5 4 3
7 2 1
6 1 1
First row is N, following rows are a cow's x, y, and p. Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int n;
int best=0;
int cnt=1;
struct cow {
int x, y, p;
bool visited=0;
} cows[201];
bool adj[201][201];
bool access (int a, int b) {
return pow(cows[b].x-cows[a].x, 2)+pow(cows[b].y-cows[a].y, 2)<=pow(cows[a].p, 2);
}
void dfs(int cow1) {
for (int i=1; i<=n; i++) {
if (cnt>best)
best=cnt;
if ((!cows[i].visited)&&(adj[cow1][i])) {
cnt=cnt+1;
cows[i].visited=1;
dfs(i);
}
}
return;
}
int main () {
cin>>n;
for (int i=1; i<=n; i++) {
cin>>cows[i].x>>cows[i].y>>cows[i].p;
}
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
if (i!=j) {
if(access(i, j)) {
adj[i][j]=1;
}
else {
adj[i][j]=0;
}
}
}
}
for (int i=1; i<=n; i++) {
cows[i].visited=1;
dfs(i);
cnt=1;
for (int j=1; j<=n; j++) {
cows[j].visited=0;
}
}
cout<<best;
}
I'm not quite sure where the issue is, but I am sure it is within the dfs function, and not within the creation of the adjacency list. My code works only for the sample case. I'm essentially doing dfs on all n cases of starting cows for the message.
The error is simple. You measure the longest path length (cow count actually). But the question is different, it is how may cows are reachable. Consider the case of three cows of which one can be heard by everyone while the others are voiceless. Your program will answer 2 (unless I missed another error) as that’s the longest chain, but the right answer is 3 (it is the count of cows visited
).