水管工游戏(啊哈!算法)
#include<iostream> using namespace std; int n,m; int map[50][50]; int book[50][50]; bool f; struct node{ int x; int y; }a[50]; int top; void dfs(int x,int y,int dir){ if(x==n && y==m+1){ f=1; for(int i=1;i<=top;i++){ cout<<'('<<a[i].x<<','<<a[i].y<<')'<<' '; } return; } top++; a[top].x=x; a[top].y=y; //straight pipe if(x>=1 &&x<=n&&y>=1 &&y<=m&&!book[x][y]){ book[x][y]=1; if(map[x][y]>=5 &&map[x][y]<=6){ if(dir ==1){ dfs(x,y+1,1); } if(dir == 2){ dfs(x+1,y,2); } if(dir == 3){ dfs(x,y-1,3); } if(dir==4){ dfs(x-1,y,4); } } if(map[x][y]>=1&&map[x][y]<=4){ if(dir==2){ dfs(x,y+1,1); dfs(x,y-1,3); } if(dir==1){ dfs(x+1,y,2); dfs(x-1,y,4); } if(dir==3){ dfs(x+1,y,2); dfs(x-1,y,4); } if(dir==4){ dfs(x,y+1,1); dfs(x,y-1,3); } } } top--; book[x][y]=0; return; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>map[i][j]; } } dfs(1,1,1); if(f==0){ cout<<"Impossible"; } return 0; }