原文链接:https://www.luogu.com.cn/problem/P3956
AC代码:
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int mapp[105][105],visit[105][105],isqueue[105][105];
int n,m;
int dir[4]={-1,0,1,0};
typedef struct node{
int x,y;
int color,w;
int flag;
bool operator <(const node &a)const{
return a.w<w;
}
}node;
node nod,nodd;
priority_queue<node> que;
void spfa(){
int i,j;
nod.x=1;nod.y=1;
nod.color=mapp[1][1];
nod.flag=0;
nod.w=0;
visit[1][1]=0;
que.push(nod);
while(que.size()!=0){
nod=que.top();que.pop();
int x=nod.x;int y=nod.y;
if(x==m&&y==m) return ;
//cout<<"i: "<<x<<" "<<y<<" "<<nod.w<<" "<<nod.flag<<" "<<nod.color<<endl;
for(i=0;i<4;i++){
x=nod.x+dir[i];y=nod.y+dir[(i+1)%4];
if(x<1||x>m||y<1||y>m) continue;
//cout<<x<<" "<<y<<" "<<mapp[x][y]<<endl;
if(mapp[x][y]==nod.color){
nodd.color=nod.color;nodd.flag=0;
nodd.x=x;nodd.y=y;
nodd.w=nod.w;
if(visit[x][y]>nodd.w){
visit[x][y]=nodd.w;
que.push(nodd);
//cout<<x<<" "<<y<<" "<<nodd.w<<" "<<nodd.flag<<" "<<nodd.color<<endl;
}
}
else{
if(mapp[x][y]==-1){
if(nod.flag==1) continue;
nodd.color=nod.color;nodd.flag=1;
nodd.x=x;nodd.y=y;
nodd.w=nod.w+2;
if(visit[x][y]>nodd.w){
visit[x][y]=nodd.w;
que.push(nodd);
//cout<<x<<" "<<y<<" "<<nodd.w<<" "<<nodd.flag<<" "<<nodd.color<<endl;
}
}
else{
nodd.color=(nod.color+1)%2;nodd.flag=0;
nodd.x=x;nodd.y=y;
nodd.w=nod.w+1;
if(visit[x][y]>nodd.w){
visit[x][y]=nodd.w;
que.push(nodd);
//cout<<x<<" "<<y<<" "<<nodd.w<<" "<<nodd.flag<<" "<<nodd.color<<endl;
}
}
}
}
}
}
int main(){
int i,j;
memset(mapp,-1,sizeof(mapp));
cin>>m>>n;
for(i=1;i<=n;i++){
int p,q,r;
cin>>p>>q>>r;
mapp[p][q]=r;
}
for(i=1;i<=m;i++){
for(j=1;j<=m;j++){
visit[i][j]=1e8;
isqueue[i][j]=0;
}
}
spfa();
if(visit[m][m]==1e8){
cout<<"-1"<<endl;
}
else{
cout<<visit[m][m]<<endl;
}
return 0;
}