西南交大算法分析与设计实验最新

走迷宫问题算法 :

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<climits>

using namespace std ;

typedef pair<int,int> PII ;

const int N = 1010 ;
int n , x1 , y1 , x2 , y2 ;
int maze[N][N] ;
int minLength = INT_MAX , pathCount ;
vector<PII>path ;
int st[N][N] ;
int dx[] = {-1 , 1 , 0 , 0 } , dy[] = { 0 , 0 , -1 , 1} ;

void dfs (int x , int y) 
{
    if (x == x2 && y == y2) {
        pathCount++ ;
        for (int i = 0 ; i < path.size() ; i++) {
            int x0 = path[i].first , y0 = path[i].second ;
            cout << "(" << x0 << "," << y0 << ")" << " " ;
        }
        puts ("") ;
        if (minLength > path.size()) minLength = path.size() ;
        
        return  ;
    }
    for (int i = 0 ; i < 4 ; i++ ){
            int x0 = x + dx[i] , y0 = y + dy[i] ;
            if (x0 >= 1 && x0 <= n && y0 >= 1 && y0 <= n && st[x0][y0] == 0 && maze[x0][y0] == 0){
                path.push_back({x0 , y0}) ;
                st[x0][y0] = 1 ;
                dfs (x0 , y0) ;
                st[x0][y0] = 0 ;
                path.pop_back() ;
            }
    }
}

int main ()
{
    cout << "请输入迷宫的维数: " ;
    cin >> n ;
    cout << "请输入迷宫的起点 : "  ;
    cin >> x1 >> y1  ;
    cout << "请输入迷宫的终点  : "  ;
    cin >> x2 >> y2 ;
    
    cout << "请输入迷宫 : " << endl ;
    for (int i = 0 ; i < n ; i++)
        for (int j = 0 ; j < n ; j++) scanf ("%d" , &maze[i][j]) ;
        
    path.push_back({x1 , y1}) ;
    st[x1][y1] = 1 ;
    dfs (x1 , y1) ; 
    
    cout << pathCount << "  " << minLength << endl ;
    
    return 0 ;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值