The question is very simple, that is, "input m rows and n columns". "Y" indicates the location of your tank, and "T" indicates your goal, on the way, "S" indicates the steel wall that cannot pass, and "R" indicates the river that cannot pass, "B" indicates that you are wasting a bullet (that is, taking one step is equivalent to taking two steps), and "E" can represent the open space. This is equivalent to the shortest path problem. Deep Search and wide search are all supported. However, I am doing deep search myself, and wide search is a code that sticks to a large bull.
The code for deep search is as follows:
#include<stdio.h>#include<string.h>int m,n,a[3],b[2],s[302][302];char map[302][302];void fun(int w,int e,int x,int y){ if(x<0||y<0||x==m||y==n) return ; if(map[x][y]=='R'||map[x][y]=='S'||map[x][y]=='Y') return ; if(x==b[0]&&y==b[1]) { if(s[x][y]==0) s[x][y]=s[w][e]+1; else { if(s[x][y]<s[w][e]+1) return ; else s[x][y]=s[w][e]+1; } } if(map[x][y]=='B') { if(s[x][y]==0) s[x][y]=s[w][e]+2; else { if(s[x][y]<s[w][e]+2) return ; else s[x][y]=s[w][e]+2; } } if(map[x][y]=='E') { if(s[x][y]==0) s[x][y]=s[w][e]+1; else { if(s[x][y]<s[w][e]+1) return ; else s[x][y]=s[w][e]+1; } } fun(x,y,x-1,y);fun(x,y,x+1,y);fun(x,y,x,y-1);fun(x,y,x,y+1);}int main(){ int k,i,j,z[5]; while(scanf("%d%d",&m,&n),m,n) { memset(s,0,sizeof(s)); for(i=0;i<m;i++) { scanf("%s",map[i]); for(j=0;j<n;j++) { if(map[i][j]=='Y') {a[0]=i;a[1]=j;} if(map[i][j]=='T') {b[0]=i;b[1]=j;} } } fun(a[0],a[1],a[0]-1,a[1]); fun(a[0],a[1],a[0],a[1]-1); fun(a[0],a[1],a[0]+1,a[1]); fun(a[0],a[1],a[0],a[1]+1); if(s[b[0]][b[1]]==0) printf("-1\n"); else printf("%d\n",s[b[0]][b[1]]); }}
The specific code of guangsearch is as follows:
#include<iostream>#include<cstdio>#include<cstdlib>#include<queue>#include<cstring>using namespace std;char map[301][301];int row,col;int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};struct node {int x;int y;int c;friend bool operator < (const node &a,const node &b){return a.c>b.c;}};node begin1,end1;priority_queue<node>data;int bfs(){int i=0;node tem;while( !data.empty() ){begin1=data.top();data.pop();if( (begin1.x==end1.x) && (begin1.y==end1.y)) return begin1.c;for(i=0;i<4;i++){tem.x=begin1.x+dir[i][0];tem.y=begin1.y+dir[i][1];if(tem.x>=0 && tem.x<row && tem.y>=0 && tem.y<col && map[tem.x][tem.y]!='1'){if(map[tem.x][tem.y]=='B'){tem.c=begin1.c+2;data.push(tem);map[tem.x][tem.y]='1';}else{if(map[tem.x][tem.y]=='E' || map[tem.x][tem.y]=='T'){tem.c=begin1.c+1;data.push(tem);map[tem.x][tem.y]='1';}}}}}return 0;}int main(){int i=0,j=0;int step;while(scanf("%d%d",&row,&col)&&(row+col)){step=0;memset(map,'\0',sizeof(map));for(i=0;i<row;i++){scanf("%s",map[i]);for(j=0;j<col;j++){if(map[i][j]=='Y'){begin1.x=i;begin1.y=j;begin1.c=0;}if(map[i][j]=='T'){end1.x=i;end1.y=j;end1.c=0;}}}data.push(begin1);map[begin1.x][begin1.y]='1';step=bfs();if(step>0)printf("%d\n",step);elseprintf("-1\n");while(!data.empty())data.pop();}return 0;}