跳跃ios
第 1 行: 四个空格分开的整数: M, N, M1, 和 M2
第 2 至 M+1行: 第i+1行用N个空格分开的整数描述池塘第i行,0表示水,1表示 荷叶,2表示岩石,3表示Bessie如今站的那块荷叶,4表示跳跃的 终点。
第 1 行: 一个整数,是Bessie从一块荷叶跳到另外一块荷叶所需的最小的跳跃数。
4 5 1 2 1 0 1 0 1 3 0 2 0 4 0 1 2 0 0 0 0 0 1 0
2
Bessie在第二行的左边开始;她的目的地在第二行的右边。池塘中有几块荷叶和岩石。
Bessie聪明的跳到了(1,3)的荷叶上,再跳到目的地。
思路:这题我狂WA了,刚开始读错题了,明明不是国际象棋马的走法,为什么非要扯上关系??(我还去百度了)多是我太菜了orzorz,写下这篇博客当教训了。
正确走法就是一共八种走法,就是上下和左右必定会走一个值,可能m1,或m2,
好比上m1,右m2->(x+m2,y+m1)或下m2,左m1->(x-m1,y-m2)
画个图就知道是八种了,这题我写dfs tle了,可能写挂了,而后用的bfs,考虑到能走的点很少,bfs更快......
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 #include<queue>
10 using namespace std; 11 #define ll long long
12
13 const int maxn=101; 14
15 int e[maxn][maxn]; 16
17 int book[maxn][maxn]; 18
19 int n,m,go1,go2; 20
21 int startx,starty; 22
23 int minn; 24
25 typedef struct
26 { 27 int x; 28 int y; 29 int cnt; 30 } St; 31
32 queue<St>q; 33
34
35 int main() 36 { 37 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 38
39 cin>>n>>m>>go1>>go2; 40
41 for(int i=1;i<=n;i++) 42 { 43 for(int j=1;j<=m;j++) 44 { 45 cin>>e[i][j]; 46 if(e[i][j]==0||e[i][j]==2) 47 e[i][j]=0; 48 else if(e[i][j]==3) 49 { 50 startx=i; 51 starty=j; 52 } 53 } 54 } 55
56 minn=inf; 57
58 book[startx][starty]=1; 59
60 St now; 61
62 now.x=startx; 63 now.y=starty; 64 now.cnt=0; 65
66 q.push(now); 67
68 while(!q.empty()) 69 { 70 now=q.front(); 71 int x=now.x; 72 int y=now.y; 73 int f=now.cnt; 74 int tx,ty; 75 for(int i=0;i<8;i++) 76 { 77 if(i==0) 78 tx=x+go1,ty=y+go2; 79 else if(i==1) 80 tx=x+go2,ty=y+go1; 81 else if(i==2) 82 tx=x-go1,ty=y+go2; 83 else if(i==3) 84 tx=x-go2,ty=y+go1; 85 else if(i==4) 86 tx=x+go1,ty=y-go2; 87 else if(i==5) 88 tx=x+go2,ty=y-go1; 89 else if(i==6) 90 tx=x-go1,ty=y-go2; 91 else if(i==7) 92 tx=x-go2,ty=y-go1; 93
94 if(tx<1||tx>n||ty<1||ty>m) 95 continue; 96
97 if(e[tx][ty]==0) 98 continue; 99
100 if(!book[tx][ty]) 101 { 102 book[tx][ty]=1; 103 now.x=tx; 104 now.y=ty; 105 now.cnt=f+1; 106
107 if(e[tx][ty]==4) 108 return cout<<now.cnt<<endl,0; 109
110 q.push(now); 111
112 } 113 } 114 q.pop(); 115 } 116 }