Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1253
Thinking Analysis: because the problem needs to find the shortest distance to reach the end (the shortest number of steps), that is, in the state conversion diagram need to find the level of the most shallow state (A-1, B-1, C-1),
So the use of BFS to find the answer faster, in addition, if the use of Dfs is more difficult, you need to traverse all States to find the results.
The code is as follows :
#include <cstdio>#include<iostream>Const intMax_n = -;structpoint{intA, B, C; intTime ; Point () {a=0; b =0; c =0; Time =0; } Point (intXintYintZintstep_time) {a= x; b = y; c = z; Time =Step_time; }};intAns =0;intA, B, C, game_times;intMap[max_n][max_n][max_n];intmove[6][3] ={{0,0, -1}, {0,0,1}, {0, -1,0}, {0,1,0}, {-1,0,0}, {1,0,0}}; Point queue[1000000];intBfs () {inthead, tail; Point temp; Head= Tail =0; Temp.a= TEMP.B = Temp.c = Temp.time =0; Queue[tail++] =temp; while(Head! =tail) {Temp= queue[head++]; for(inti =0; I <6; ++i) {intNext_a = Temp.a + move[i][0]; intNext_b = temp.b + move[i][1]; intNext_c = temp.c + move[i][2]; if(Next_a <0|| Next_b <0|| Next_c <0|| Next_a >= A | | Next_b >= B | | Next_c >=C|| Map[next_a][next_b][next_c] >0|| Temp.time +1>game_times)Continue; if(Next_a = = A-1&& Next_b = = B-1&& Next_c = = C-1) returnTemp.time +1; Point Next (Next_a, Next_b, Next_c, Temp.time+1); Map[next_a][next_b][next_c]=Next.time; Queue[tail++] =Next; } } return-1;}intMain () {intK; scanf ("%d", &k); while(k--) {scanf ("%d %d%d%d", &a, &b, &c, &game_times); for(inti =0; i < A; ++i) for(intj =0; J < B; ++j) for(intK =0; K < C; ++k) scanf ("%d", &Map[i][j][k]); printf ("%d\n", Bfs ()); } return 0;}
Hdoj 1253 Victory Grand Escape (BFS)