路径是可以重复走的,但是如果再一次走过时间重置点是没有意义的
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <queue> using namespace std; const int N = 100; int mp[N][N]; struct Node { int x, y, step, time; }; int m, n; int dir[4][2] = {1,0, 0,1, -1,0, 0,-1}; int bfs(int x, int y) { queue<Node> que; Node start; start.x = x; start.y = y; start.step = 0; start.time = 6; que.push(start); while(!que.empty()) { Node cur = que.front(); que.pop(); if(cur.time == 0) continue; for(int i=0; i<4; i++) { int tx = cur.x+dir[i][0]; int ty = cur.y+dir[i][1]; Node nextstep; nextstep.x = tx; nextstep.y = ty; nextstep.step = cur.step+1; nextstep.time = cur.time-1; if(tx<0 || ty<0 || tx>=m || ty>=n) { continue; } if(mp[tx][ty] == 0) continue; if(mp[tx][ty] == 3) { if(nextstep.time>0) return cur.step+1; else continue; } if(mp[tx][ty] == 4) { if(nextstep.time>0){ nextstep.time = 6; mp[tx][ty] = 0; //只能走一次,走多了就没有意义了 } else { continue; } } que.push(nextstep); } } return -1; } int main() { int t; cin>>t; while(t--) { cin>>m>>n; int x, y; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cin>>mp[i][j]; if(mp[i][j] == 2) { x = i; y = j; } } } cout<<bfs(x, y)<<endl; } return 0; }