还能如何优化,请求指教
#include<bits/stdc++.h>
using namespace std;
int n,m,ans=1e+3,uke[101][3],uk;
int k[101][101],hx[4]={0,0,1,-1},hy[4]={-1,1,0,0};
bool s[101][101];
bool pc(int x,int y){
if(x<1||x>n||y<1||y>n||s[x][y]){
return 0;
}
return 1;
}
bool dfs(int x,int y,int q,int r,int t,int w){
if(r)
w=k[x][y];
if(q>=ans)
return 0;
if(x==n&&y==n){
ans=q;
return 1;
}
s[x][y]=1;
int v=0;
for(int i=0;i<=3;i++){
int ex=x+hx[i],ey=y+hy[i],mon=q;
if(!pc(ex,ey))
continue;
if(k[ex][ey]!=w&&k[ex][ey]){
if(dfs(ex,ey,mon+1,1,t+1,k[x][y])){
v=1;
}
}
else
if(!k[ex][ey]&&r){
if(dfs(ex,ey,mon+2,0,t+1,k[x][y])){
v=1;
}
}
else
if(k[ex][ey]==w){
if(dfs(ex,ey,mon,1,t+1,k[x][y])){
v=1;
}
}
}
s[x][y]=0;
return v;
}
int main(){
int xx,yy,c;
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>xx>>yy>>c;
if(!c){
c=2;
}
k[xx][yy]=c;
}
int w=dfs(1,1,0,1,0,k[1][1]);
if(w){
cout<<ans<<endl;}
else
cout<<-1<<endl;
return 0;
}