當前位置:
首頁 >
猫和老鼠 蓝桥杯/手速/暴力练习赛(暴力搜索)
發布時間:2025/3/8
34
豆豆
生活随笔
收集整理的這篇文章主要介紹了
猫和老鼠 蓝桥杯/手速/暴力练习赛(暴力搜索)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
貓和老鼠 藍橋杯/手速/暴力練習賽
【題目描述】貓和老鼠在10*10 的方格中運動,例如:*...*...........*......*...*...............*.C....*.....*......*........M......*...*.*.....*.*......C=貓(CAT)M=老鼠(MOUSE)*=障礙物.=空地貓和老鼠每秒中走一格,如果在某一秒末他們在同一格中,我們稱他們“相遇”。注意,“對穿”是不算相遇的。貓和老鼠的移動方式相同:平時沿直線走,下一步如果會走到障礙物上去或者出界,就用1 秒的時間做一個右轉90 度。一開始他們都面向北方。編程計算多少秒以后他們相遇。【輸入格式】10 行,格式如上【輸出格式】相遇時間T。如果無解,輸出-1。【樣例輸入】*...*...........*......*...*...............*.C....*.....*......*........M......*...*.*.....*.*......
1 /*
2 思路:如果貓和老鼠不相遇,那么一定是貓在某一個格子沿著某一個方向重復走了2次以上并且
3 老鼠也是這樣。
4 */
5 #include<iostream>
6 #include<cstring>
7 #include<cstdio>
8 #include<algorithm>
9 using namespace std;
10
11 char mp[15][15];
12
13 const int left_dir = 1;
14 const int right_dir = 2;
15 const int up = 3;
16 const int down = 4;
17 const int mouse = 1;
18 const int cat = 0;
19
20 struct node{
21 int x, y;
22 int dir;
23 node(){
24 dir = up;
25 }
26
27 bool flag[15][15][5];//記錄當前格子在某一個方向上是否走過
28
29 void init(int x, int y){
30 memset(flag, false, sizeof(flag));
31 this->x = x;
32 this->y = y;
33 flag[x][y][up] = true;
34 }
35 };
36
37 node nd[2];
38 int cnt = 0;
39
40 bool move(int i){
41 int x=nd[i].x, y=nd[i].y;
42 int newdir;
43 switch(nd[i].dir){
44 case up:
45 x-=1;
46 newdir = right_dir;
47 break;
48 case down:
49 x+=1;
50 newdir = left_dir;
51 break;
52 case left_dir:
53 y-=1;
54 newdir = up;
55 break;
56 case right_dir:
57 y+=1;
58 newdir = down;
59 break;
60 }
61 if(mp[x][y] != '*'){
62 nd[i].x = x;
63 nd[i].y = y;
64 } else {
65 nd[i].dir = newdir;
66 }
67
68 if(!nd[i].flag[x][y][nd[i].dir]){
69 nd[i].flag[x][y][nd[i].dir] = true;
70 return true;
71 } else return false;
72 }
73
74 void test(){
75 bool flag = true, flag1=false, flag2=false;
76 while(flag){
77 if(nd[cat].x == nd[mouse].x && nd[cat].y == nd[mouse].y) break;
78 if(!move(cat))
79 flag1 = true;
80 if(!move(mouse))
81 flag2 = true;
82 ++cnt;
83 if(flag1 && flag2) flag = false;
84 }
85 if(flag) printf("%d\n", cnt);
86 else printf("-1\n");
87 }
88
89 int main() {
90 memset(mp, '*', sizeof(mp));
91 for(int i=1; i<=10; ++i){
92 scanf("%s", mp[i]+1);
93 mp[i][strlen(mp[i]+1)+1] = '*';
94 for(int j=1; j<=10; ++j){
95 if(mp[i][j]=='C'){
96 nd[cat].init(i, j);
97 mp[i][j] = '.';
98 }
99 else if(mp[i][j] == 'M'){
100 nd[mouse].init(i, j);
101 mp[i][j] = '.';
102 }
103 }
104 getchar();
105 }
106 test();
107 return 0;
108 }
109 /*
110 *...*.....
111 ......*...
112 ...*...*..
113 ..........
114 ...*.C....
115 *.....*...
116 ...*......
117 ..M......*
118 ...*.*....
119 .*.*......
120 */
?
轉載于:https://www.cnblogs.com/hujunzheng/p/4415666.html
總結
以上是生活随笔為你收集整理的猫和老鼠 蓝桥杯/手速/暴力练习赛(暴力搜索)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android计算距离顶部的距离,(lu
- 下一篇: lintcode循环数组之连续子数组求和