递归函数,变量定义在全局出错,局部正确

清晨曦月 清晨曦月 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
情况,这是一个NOIP的问题,做这个题的时候发现一个问题,TX和TY如果定义为全局变量,在DEVC++中会非法操作,在VS中虽然不出错但是结果不正确,但如果定义为局部变量,就不会出现问题,出错代码如下:

#include<iostream>
#include<memory.h>
using namespace std;

int arr[11][11]={0};
int t,n,m,x,y,tx,ty,cnt=0; //***********************
//x在前
int dir[8][2]={{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2}};
//点x,点y,计数
void Dfs(int x,int y,int ans){ //重命名了 ,但是局部变量优先级高于全局,代码逻辑没错误
if(ans==m*n){
cnt++;
}else{
for(int i=0;i<8;i++){
tx=x+dir[i][0]; //**************
ty=y+dir[i][1]; //**************
if(tx>=0 && tx<n && ty>=0 && ty<m && arr[ty][tx]!=1){ //m, 打成n了
arr[ty][tx]=1;
Dfs(tx,ty,ans+1);
arr[ty][tx]=0;
}
}
}
}

int main(){
cin>>n>>m>>x>>y;
memset(arr, 0, sizeof(arr));
cnt=0;
arr[y][x]=1; //1=走过
Dfs(x,y,1);
cout<<cnt<<endl;
return 0;
}


如果把这两个变量定义为局部变量,就可以得到正确结果:

#include<iostream>
#include<memory.h>
using namespace std;

int arr[11][11]={0};
int t,n,m,x,y,cnt=0;
//x在前
int dir[8][2]={{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2}};
//点x,点y,计数
void Dfs(int x,int y,int ans){ //重命名了 ,但是局部变量优先级高于全局,代码逻辑没错误
if(ans==m*n){
cnt++;
}else{
for(int i=0;i<8;i++){
int tx=x+dir[i][0]; //未知问题,变量定义在这里使用栈空间就没问题了.
int ty=y+dir[i][1]; //占用全局变量空间就会发生错误
if(tx>=0 && tx<n && ty>=0 && ty<m && arr[ty][tx]!=1){ //m, 打成n了
arr[ty][tx]=1;
Dfs(tx,ty,ans+1);
arr[ty][tx]=0;
}
}
}
}

int main(){
cin>>n>>m>>x>>y;
memset(arr, 0, sizeof(arr));
cnt=0;
arr[y][x]=1; //1=走过
Dfs(x,y,1);
cout<<cnt<<endl;
return 0;
}


测试数据:5 4 0 0,
正确结果:32
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
清晨曦月
清晨曦月 领域专家: 嵌入式与硬件开发技术领域 领域专家: 嵌入式与硬件开发技术领域
C++ 语言 65,214 成员 250,514 内容