⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 猫和老鼠.cpp

📁 猫捉老鼠问题的实现
💻 CPP
字号:
#include<iostream>
using namespace std;

enum Way{up,right,down,left};
typedef struct{int x,y;Way d;}Point;
class road
{
public:
    road();
    int getit();
    void move();
    int seconds;
private:
    int item[10][10];
    Point Cat,Mouse;
    void Fill(char s,int x,int y);
    int canmove(Point& pos);
};
int main()
{
    int data;
	cout<<"输入组数:"<<endl;
    cin>>data;
	cout<<"输入猫和老鼠图示:"<<endl;
    road* m;
    while(data-- > 0)
    {
        m=new road();
        while(!m->getit())
        {
            m->move();
            if(m->seconds>160000l)
            {
                m->seconds = -1;
                break;
            }
        }
		cout<<"猫捉老鼠:"<<endl;
        cout<<"猫走"<<m->seconds<<"步,能捉到老鼠!"<<endl;
    }
    return 0;
}
road::road()
{
    char s[10];
    int count1,count2;
    for(count1=0;count1<10;count1++)
    {
        cin>>s;
        for(count2=0;count2<10;count2++)
            Fill(s[count2],count1,count2);
    }
    seconds = 0;
    Cat.d = Mouse.d = up;
}
int road::getit()
{return (Cat.x==Mouse.x && Cat.y==Mouse.y);}
void road::Fill(char s,int x,int y)
{
    switch(s)
    {
    case '*': item[x][y]=0;break;
    case '.': item[x][y]=1;break;
    case 'C': item[x][y]=1;Cat.x=x,Cat.y=y;break;
    case 'M': item[x][y]=1;Mouse.x=x,Mouse.y=y;break;
    }
}
void road::move()
{
    if(!canmove(Cat)) Cat.d=(Way)((Cat.d+1)%4);
    if(!canmove(Mouse)) Mouse.d=(Way)((Mouse.d+1)%4);
    seconds++;
}
int road::canmove(Point& pos)
{
    switch(pos.d)
    {
    case up:
        if(0!=pos.x && item[pos.x-1][pos.y]){pos.x--;return 1;}
        break;
    case right:
        if(9!=pos.y && item[pos.x][pos.y+1]){pos.y++;return 1;}
        break;
    case down:
        if(9!=pos.x && item[pos.x+1][pos.y]){pos.x++;return 1;}
        break;
    case left:
        if(0!=pos.y && item[pos.x][pos.y-1]){pos.y--;return 1;}
        break;
    }
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -