dfs模板(真心不会深搜)


#include #include char Map[16][16]; int mv[16][16]; int jx[] = { 0,-1, 0, 1}; int jy[] = { 1, 0,-1, 0}; int Min; void dfs(int x,int y,int n,int m,int ans) { int xx,yy; if(ans >= Min) { return ; } if(Map[x][y] == 'Y') { if(ans < Min) { Min = ans; } return ; } for(int i = 0; i < 4; ++i) { xx = x + jx[i]; yy = y + jy[i]; if(0 <= xx && xx < n && 0 <= yy && yy < m && mv[xx][yy] == 0 && Map[xx][yy] != '#') { mv[xx][yy] = 1; dfs(xx,yy,n,m,ans+1); mv[xx][yy] = 0; } } } int main() { int n,m,i,j; while(scanf("%d %d",&n,&m) != EOF) { memset(mv,0,sizeof(mv)); for(i = 0; i < n; ++i) { scanf("%*c%s",Map[i]); } for(i = 0; i < n; ++i) { for(j = 0; j < m; ++j) { if(Map[i][j] == 'X') break; } if(j != m) break; } Min = (1<<20); dfs(i,j,n,m,0); if(Min == (1<<20)) { printf("-1\n"); } else { printf("%d\n",Min); } } return 0; }

【dfs模板(真心不会深搜)】

    推荐阅读