top1编程
← 返回题目
题解

迷宫

1 条题解

  • 0
    @ 2026-7-28 22:45:20
    #include <iostream>
    using namespace std;
    
    int a[150][150],n,x1,y1,x2,y2;
    bool f = false;//表示有没有走到 
    
    //从x、y点开始逐步探测 
    void num(int x,int y){
    	if(x == x2 && y == y2){
    		f = true;
    	}else{
    		a[x][y] = 1;//探测过的点,设置为不可探测,防止重复的探测 
    		//上下左右探测,且不越界 
    		if(x - 1 >= 1 && a[x - 1][y] == 0) num(x-1,y);
    		if(x + 1 <= n && a[x + 1][y] == 0) num(x+1,y);
    		if(y - 1 >= 1 && a[x][y - 1] == 0) num(x,y - 1);
    		if(y + 1 <= n && a[x][y + 1] == 0) num(x,y + 1);
    	}
    } 
    
    int main(){
    	int i,j;
    	cin>>n;
    	//0表示能走,1表示不能走 
    	for(i = 1;i <= n;i++){
    		for(j = 1;j <= n;j++){
    			cin>>a[i][j];
    		}
    	}
    	cin>>x1>>y1>>x2>>y2;
    	
    	//如果起止点有1,则不需要探测 
    	if(a[x1][y1] == 1 || a[x2][y2] == 1){
    		cout<<"NO"<<endl; 
    	}else{
    		num(x1,y1);
    		//探测完测试,如果走到了 
    		if(f == true){
    			cout<<"YES"<<endl; 
    		}else{
    			cout<<"NO"<<endl;
    		}
    	} 
    }
    
    • 1