111

#include<iostream>
#include <vector>
//在3x3迷宫中寻找从S(0,0)到E(2,2)的所有路径
using namespace std;
int m=999;
vector<pair<int,int>> path;//存储路径坐标
vector<pair<int,int>> path1;
bool v[3][3]={false};//标记已访问位置
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向
void dfs(int x,int y,int step){
    //1:终止条件 
    if(x==2&&y==2){
    	for(auto a:path){
            cout<<"("<<a.first<<","<<a.second<<")"; 
        }
        cout<<endl<<step<<endl;
        m=min(m,step);
        if(step==m){
        	path1.clear();
        	for(auto a:path){
        		path1.push_back({a.first,a.second});
			}
		}
        return;
    }
    //2.循环所有条件
    for(auto b:d){
        int nx=x+b[0],ny=y+b[1];
        if(nx>=0&&nx<=2&&ny>=0&&ny<=2&&v[nx][ny]!=true){
            v[nx][ny]=true;
            path.push_back({nx,ny});
            dfs(nx,ny,step+1);
            //3.回溯
            path.pop_back();
            v[nx][ny]=false;
        }
    }
}
int main(){
    path.push_back({0,0});
    v[0][0]=true;
    dfs(0,0,0);
    for(auto a:path1){
    	cout<<"->("<<a.first<<","<<a.second<<")";
	}
    return 0;
}

  

posted @ 2025-04-26 15:50  陈若麟  阅读(11)  评论(0)    收藏  举报