【NOIP2017】 棋盘
解题思路:
从左上向右下搜索,然后来一点剪枝就可以了,比较简单,毫无体验感
AC代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int inf=0x7fffffff; int m,n; int map[105][105]; int s[105][105]; int sx[4]={-1,0,1,0}; int sy[4]={0,-1,0,1}; int ans=inf; void dfs(int x,int y,int cost,bool use) { if(x<1||y<1||x>m||y>m) return ; if(cost>=s[x][y]) return ; s[x][y]=cost; if(x==m&&y==m) { if(cost<ans) ans=cost; return ; } for(int i=0;i<4;i++) { int xx=x+sx[i]; int yy=y+sy[i]; if(map[xx][yy]) { if(map[xx][yy]==map[x][y]) dfs(xx,yy,cost,false); else dfs(xx,yy,cost+1,false); } else if(!use) { map[xx][yy]=map[x][y]; dfs(xx,yy,cost+2,true); map[xx][yy]=0; } } } int main() { memset(s,0x7f,sizeof(s)); cin>>m>>n; for(int i=1;i<=n;i++) { int x,y,c; cin>>x>>y>>c; map[x][y]=c+1; } dfs(1,1,0,false); printf("%d", ans==inf ? -1 : ans); return 0; }
|