一开始用dfs做的 超时了然后又用了bfs才A掉的
3 3 X#Y *** #*# 3 3 X#Y *#* #*#
4 -1
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int x, y, z; }Q[410],ans; char Map[20][20]; int book[20][20]; int x1,x2,y1,y2; int dx[] = {0,0,-1,1}; int dy[] = {1,-1,0,0}; int bfs(int n, int m) { memset(book,0,sizeof(book)); Q[0] = {x1,y1,0}; book[x1][y1] = 1; int head =0, tail = 1; while(head < tail){ ans = Q[head]; head++; if(ans.x==x2&&ans.y==y2){ return ans.z; } for(int i = 0;i < 4;i++){ int nowx = ans.x+dx[i]; int nowy = ans.y+dy[i]; if(nowx>=1&&nowx<=n&&nowy>=1&&nowy<=m &&Map[nowx][nowy]!='#'&&!book[nowx][nowy]){ Q[tail++] = {nowx,nowy,ans.z+1}; book[nowx][nowy] = 1; } } } return -1; } int main() { int n, m; while(~scanf("%d %d", &n, &m)){ int i, j; for(i = 1;i<=n;i++){ scanf("%s", Map[i]+1); for(j = 1;j <= m;j++){ if(Map[i][j] == 'X'){ x1 = i; y1 = j; } if(Map[i][j] == 'Y'){ x2 = i; y2 = j; } } } printf("%d\n", bfs(n,m)); } return 0; }这是可以A掉的
下面为DFS的代码 Tle 啊
#include <stdio.h> #include <string.h> #include <stdlib.h> int startx,starty; int n, m; char Map[20][20]; int book[20][20]; int dx[] = {-1,1,0,0}; int dy[] = {0,0,-1,1}; int tx,ty; int ans; void dfs(int x, int y, int step) { if(x==tx && y== ty){ if(step < ans){ ans = step; } return; } int nowx, nowy; int i; for(i =0;i < 4;i++){ nowx = x+dx[i]; nowy = y+dy[i]; if(nowx>=1&&nowx<=n&&nowy>=1&&nowy<=m&& Map[nowx][nowy]!='#'&&!book[nowx][nowy]){ book[nowx][nowy] = 1; dfs(nowx,nowy,step+1); book[nowx][nowy] =0; } } } int main() { while(~scanf("%d %d", &n, &m)){ ans = 0x3f3f3f3f; memset(book,0,sizeof(book)); int i,j; for(i = 1;i <=n;i++){ scanf("%s", Map[i]+1); for(j = 1;j <= m;j++){ if(Map[i][j] == 'X'){ startx = i; starty = j; } if(Map[i][j] == 'Y'){ tx = i; ty = j; } } } book[startx][starty] = 1; dfs(startx, starty,0); if(ans == 0x3f3f3f3f){ printf("-1\n"); }else { printf("%d\n", ans); } } return 0; }