| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1540 人关注过本帖
标题:罗密欧与朱丽叶 迷宫问题
只看楼主 加入收藏
diaoxue
Rank: 1
等 级:新手上路
帖 子:142
专家分:0
注 册:2007-6-1
收藏
 问题点数:0 回复次数:0 
罗密欧与朱丽叶 迷宫问题
我想输出每次的方向,没有输出,(全0)调用函数后表明都遍历到了
/*m=8
n=8
1 2   3 7   5 5   8 2
luo   3 3 p q
zhu   6 6 r s
*/
#include <iostream>
#include <iomanip>
using namespace std;
int Min=1000;
const int M=100;
int direct[M]={0};
int best[M]={0};
const int m=8;
const int n=8;
const int p=2;
const int q=2;
const int r=5;
const int s=5;
int a[m][n]={0};
int b[4][2]={{0,1},{2,6},{4,4},{7,1}};
int c[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
static int count=0;
int i=0;
void Init()//创建迷宫
{
    int i,j;
/*    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            a[i][j]=-1;*/
    for(i=0;i<4;i++)
        a[b[i][0]][b[i][1]]=-1;
    a[p][q]=1;
    a[r][s]=1;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
            //cout<<a[i][j]<<"\t";
            cout<<setw(3)<<a[i][j];
        cout<<endl;
    }
    cout<<"===============================";
    cout<<"==============================="<<endl;
}
bool Ok()//所有的方格都走了一遍
{
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
            if(a[i][j]==0)
                return false;
    }
    return true;
}
//bool Pass(int x,int y,int dir)
bool Pass(int &x,int &y,int dir)
{
    x=x+c[dir][0];
    y=y+c[dir][1];
    if(x<0 || x>=8 || y<0 || y>=8 || a[x][y]!=0) //不能通过
    {
        x=x-c[dir][0];
        y=y-c[dir][1];
        return false;
    }
    else
        return true;
}
void Mazebt(int x,int y)//回溯 迷宫问题
{
//    int x=p,y=q;
    if(Ok() && x==r && y==s)//pro
    {
        if(count<Min)
        {
            Min=count;
            cout<<"The love path is found!"<<endl;
            for(int j=0;j<M;j++)
            {
                best[j]=direct[j];
                cout<<best[j]<<"\t";
            }
            cout<<endl;
        }
    }
    int dir=0;
    for(dir=0;dir<8;dir++)
    {
        if(Pass(x,y,dir))
        {
            direct[i]=dir;//记下方向
            i++;
            a[x][y]=1;//经过,做标记
            Mazebt(x,y);
        }
        count++;
    }
}
int main()
{
    Init();
    int x=p,y=q;
    Mazebt(x,y);
    for(int k=0; k<m; k++)            //输出迷宫地形;0:代表可走,-1:不可走;
    {
        for(int l=0; l<n; l++)
            cout<<setw(3)<<a[k][l];
        cout<<endl;
    }
    cout<<endl;
    cout<<endl;
//    for(int j=0;j<M;j++)
//        cout<<setw(3)<<best[j];
    return 0;
}
搜索更多相关主题的帖子: 罗密欧 朱丽叶 迷宫 
2007-12-29 16:35
快速回复:罗密欧与朱丽叶 迷宫问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011785 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved