试题 算法提高 Cat And Mouse(模拟)

比结果大一,但是基本步骤没错,我麻了,只能强行减一了,不过能过蓝桥杯

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
char map[20][20];
//0北,1东,2南,3,西;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//方位向量
int cnt;

struct {//x,y,方向
	int x, y;
	int dir;
} cat, mouse;

void change(int &x, int &y, int &f) {//移动
	for (int i = 0; i < 4; i ++) {//四个方向
		int xx = x + dx[i];
		int yy = y + dy[i];
		if ((map[xx][yy] == '*' || xx > 10 || yy > 10 || xx < 1 || yy < 1) && f == i)//特殊情况,遇到'*',或者到达边界;
		{
			f = (f + 1) % 4;//改变方向
			if (i == 3 && f == 0) //特判
			{
				x += -1, y += 0;
				break;
			}
		} else if (f == i) {//方向确认返回
			x = xx;
			y = yy;
			break;
		}
	}
}

void cat_mouse_game(char map[20][20], int cx, int cy, int cf, int mx, int my, int mf){
	if (cat.x == mouse.x && cat.y == mouse.y) {//退出条件
		cout << cnt - 1;
		return ;
	}
	change(cat.x, cat.y, cat.dir);//🐱移动
	change(mouse.x, mouse.y, mouse.dir);//老鼠移动
	cnt ++;
	cat_mouse_game(map, cat.x, cat.y, cat.dir, mouse.x, mouse.y, mouse.dir);递归
}

int main() {
	for (int i = 1; i <= 10; i ++) {
		for (int j = 1; j <= 10; j ++)
			cin >> map[i][j];
	}
	cat.x = 5, cat.y = 6, cat.dir = 0;
	mouse.x = 8, mouse.y = 3, mouse.dir = 0;
	map[5][6] = '.', map[8][3] = '.';
	cat_mouse_game(map, 5, 6, 0, 8, 3, 0);
	return 0;
}
posted @   帝宝单推人!  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示