https://ac.2333.moe/Problem/view.xhtml?id=1642
In the first case, it is possible to use a BFS priority queue directly.
In the second case, the path is recorded and a three-dimensional array is used to prevent the dead loop.
#include <cstdio>#include<iostream>#include<cstring>#include<queue>#include<algorithm>using namespacestd;Chars[ -];intN,m,r1,c1,r2,c2,ans1,ans2;intmap[ -][ -],vis[ -][ -],use[ -][ -][5];intdir[4][2]={1,0,0,1,-1,0,0,-1};structnode{intX,y,sum,op;};BOOL operator<(Node A, Node B) {returnA.sum>b.sum;}intCheckintXinty) { if(x>=0&&x<n&&y>=0&&y<m)return 1; return 0;}voidbfs1 () {priority_queue<node>p; Node P,q,next; P.x=r1;p.y=C1; memset (Vis,0,sizeof(VIS)); VIS[P.X][P.Y]=1; P.sum=MAP[R1][C1]; Q.push (P); while(!Q.empty ()) {Q=Q.top (); Q.pop (); if(q.x==r2&&q.y==C2) {ans1=q.sum; return; } for(intI=0;i<4; i++) {Next.x=q.x+dir[i][0]; Next.y=q.y+dir[i][1]; if(!check (NEXT.X,NEXT.Y) | | vis[next.x][next.y]| | map[next.x][next.y]==-1) Continue; Next.sum=q.sum+Map[next.x][next.y]; VIS[NEXT.X][NEXT.Y]=1; Q.push (next); } } return;}voidbfs2 () {priority_queue<node>Q; Node P,q,next; P.x=r1;p.y=C1; P.sum=MAP[R1][C1]; memset (use,0,sizeof(use)); P.op=-1; Q.push (P); while(!Q.empty ()) {Q=Q.top (); Q.pop (); if(q.x==r2&&q.y==C2) {Ans2=q.sum; return; } for(intI=0;i<4; i++) { if(i==Q.op)Continue; Next.x=q.x+dir[i][0]; Next.y=q.y+dir[i][1]; if(!check (NEXT.X,NEXT.Y) | | use[q.x][q.y][i]| | map[next.x][next.y]==-1) Continue; Next.sum=q.sum+Map[next.x][next.y]; Use[q.x][q.y][i]=1; Next.op=i; Q.push (next); } } return;} Main () {inti,j,k,cas=1; while(SCANF ("%d%d%d%d%d%d", &N,&M,&R1,&C1,&R2,&C2)! =EOF) {R1--, R2--, C1--, c2--; for(i=0; i<n;i++) { for(j=0; j<m;j++) {scanf ("%s", s); intLen=strlen (s);intVir=0; if(s[0]=='*') map[i][j]=-1; Else { for(k=0; k<len;k++) Vir=vir*Ten+s[k]-'0'; MAP[I][J]=Vir; } }} ans1=-1; ans2=-1; BFS1 (); BFS2 (); printf ("Case %d:%d%d\n", cas++, ANS1,ANS2); }}
Nbut 1642 A simple graph theory question? BFS Memory Search + Priority queue