题目大意:
巨大流星雨即将袭来。每个流星会对击中的地方以及周围(上下左右四格)造成破坏。Bessie开始时位于(0, 0)位置,并希望逃到一处不会被袭击到的地方(在第一象限内)。已知每移动一格需要1个时间单位,被流星破坏后的地方不能再进入。给出M个流星在T时刻击中的地方(X, Y),问Bessie能否逃到安全的地方,若能输出最短时间,否则输出-1。
裸的广搜,注意判重即可
#include <iostream> #include <memory.h> #include <vector> #include <queue> #include <stdio.h> #include <algorithm> #define IN (1<<28) using namespace std; struct node { int x,y,step; node( int xx = 0, int yy = 0, int ss = 0):x(xx), y(yy), step(ss){} }; queue<node> q; int Map[405][405], M, visited[405][405]; int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, 1, -1}; int ans; void bfs() { if( Map[0][0] == 0 ) { ans = -1; return; } visited[0][0] = 1; q.push( node(0,0,0) ); while( !q.empty() ) { node now = q.front(); q.pop(); if( Map[now.x][now.y] == IN ) { ans = now.step; return; } for( int i = 0; i < 4; i++ ) { int nowx = now.x + dx[i]; int nowy = now.y + dy[i]; int nowstep = now.step + 1; if( nowstep < Map[nowx][nowy] && nowx >= 0 && nowy >= 0 && !visited[nowx][nowy] ) { visited[nowx][nowy] = 1; q.push( node( nowx, nowy, nowstep) ); } } } ans = -1; return; } int main() { scanf("%d", &M ); memset(visited, 0, sizeof(visited)); for( int i = 0; i < 305; i++ ) for( int j = 0; j < 305; j++ ) { Map[i][j] = IN; } for( int i = 1; i <= M; i++ ) { int xtmp, ytmp, t; scanf("%d %d %d", &xtmp, &ytmp, &t); Map[xtmp][ytmp] = min( Map[xtmp][ytmp], t ); for( int j = 0; j < 4; j++ ) { int x = xtmp + dx[j]; int y = ytmp + dy[j]; if( x >= 0 && y >= 0 ) { Map[x][y] = min( Map[x][y], t ); } } } bfs(); printf("%d\n", ans); return 0; }