函数接收的值与传递的值不同 我用C++编写了一个简单的DFS代码,但是我传递的值和函数接收的值是不同的。打印函数接收到的值说明了这一点

函数接收的值与传递的值不同 我用C++编写了一个简单的DFS代码,但是我传递的值和函数接收的值是不同的。打印函数接收到的值说明了这一点,c++,function,c++14,depth-first-search,C++,Function,C++14,Depth First Search,你能帮帮我吗 #include <bits/stdc++.h> using namespace std; void dfs(int i, int j); char graph[51][51]; int n, m, loop = 0, inx, iny, completed = 0; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int i, j, k, a, b,

你能帮帮我吗

#include <bits/stdc++.h>

using namespace std;

void dfs(int i, int j);
char graph[51][51];
int n, m, loop = 0, inx, iny, completed = 0;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int i, j, k, a, b, c;
  cin >> n >> m;

  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      cin >> graph[i][j];
    }
  }

  for (i = 1; i <= n, completed == 0; i++) {
    for (j = 1; j <= m, completed == 0; j++) {
      inx = i;
      iny = j;
      dfs(i, j);
    }
  }

  if (completed == 1)
    cout << "YES\n";
  else
    cout << "NO\n";

  return 0;
}

void dfs(int i, int j) {
  cout << i << " " << j << "\n"; // for checking values taken by the function

  if (completed)
    return;

  if (i == inx && j == iny) {
    if (loop >= 4)
      completed = 1;
    return;
  }

  // loop will increase exponentially !!!!!!
  int k = loop;
  if (j < m && graph[i][j] == graph[i][j + 1]) {
    loop++;
    dfs(i, j + 1);
  }

  loop = k;
  if (j > 1 && graph[i][j] == graph[i][j - 1]) {
    loop++;
    dfs(i, j - 1);
  }

  loop = k;
  if (i > 1 && graph[i][j] == graph[i - 1][j]) {
    loop++;
    dfs(i - 1, j);
  }

  loop = k;
  if (i < n && graph[i][j] == graph[i + 1][j]) {
    loop++;
    dfs(i + 1, j);
  }
}
#包括
使用名称空间std;
无效dfs(int i,int j);
字符图[51][51];
int n,m,loop=0,inx,iny,completed=0;
int main(){
ios_base::与_stdio同步(false);
cin.tie(0);
cout.tie(0);
int i,j,k,a,b,c;
cin>>n>>m;
对于(i=1;i图[i][j];
}
}

对于(i=1;i)至少部分问题是,您不理解C++中操作符如何工作。


for(i=1;i这就是为什么我说它是非主题的。更多关于主题:例如警告“for(i=1;我接受不同于提供的值)”除了特定的多线程场景(另一个线程无效地覆盖当前线程的堆栈),在15年的专业软件开发中,我从未见过这种情况发生。但是你在任何递归调用中都会写出来,输出可能很容易混淆。你可以尝试根据调用深度缩进,这会让你对正在发生的事情有一个更好的印象。不能用我缩短的变体复制:
int main(int argc,char*argv[]){memset(graph,0,sizeof(graph));n=m=4;for(int i=1;i WOW……。感谢这一点。这件事没有解释。替换它会导致循环超出预期的范围。因为
dfs()
是递归的,您可能会对传递给哪个递归调用的值感到困惑。至少第一个值应该是正确的。第一个打印值应该是1。不是吗?视情况而定。如果不知道您向程序提供的输入是什么-因为您没有提供输入的示例-就不可能说根据输入到程序中的值,有很多方法可以使程序具有未定义的行为,特别是当数组索引关闭1时(C++数组索引是基于零的)。当行为未定义时,结果可能与直觉相反-并且没有必要解释它以任何特定方式显示的原因。我认为您可以尝试提供的问题链接。它包含一些测试用例。