題目大意:spa
Bessie 爲了躲避流星攻擊,從原點出發每秒移動一格。流星在T時會砸到一個座標,該座標和周圍四個格都會被破壞。問Bessie最短需花多少時間逃離到永遠不會遭到襲擊的地方。code
Inputblog
* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Tithree
Outputget
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.input
Sample Inputstring
4 0 0 2 2 1 2 1 1 2 0 3 5
Sample Outputit
5
用廣度優先搜索,判斷好條件便可
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 int dir[][2] = {{0,1}, {0,-1},{-1,0},{1,0}}; 8 9 int m; 10 int dtime[302][302]; 11 int ptime[302][302]; 12 13 typedef pair<int, int> Point; 14 queue <Point> que; 15 int main(int argc, char const *argv[]) 16 { 17 //freopen("input.txt","r",stdin); 18 scanf("%d",&m); 19 for(int i = 0; i < 302; i++) { 20 for(int j = 0; j < 302; j++) { 21 dtime[i][j] = 1002; 22 ptime[i][j] = -1; 23 } 24 } 25 while(m--) { 26 int a, b, d; 27 scanf("%d %d %d",&a,&b,&d); 28 dtime[a][b] = min(dtime[a][b],d); 29 for(int i = 0; i < 4; i++) { 30 int tx = a + dir[i][0]; 31 int ty = b + dir[i][1]; 32 if(tx >= 0 && ty >= 0 && tx < 302 && ty < 302) { 33 dtime[tx][ty] = min(dtime[tx][ty], d); 34 } 35 } 36 } 37 que.push(Point(0,0)); 38 ptime[0][0] = 0; 39 int min = 9999999; 40 41 while(!que.empty()) { 42 Point tp = que.front(); que.pop(); 43 int tpx, tpy; 44 int t = ptime[tp.first][tp.second]; 45 if(t > min) { 46 continue; 47 } 48 if(dtime[tp.first][tp.second] == 1002) { 49 if(t < min) { 50 min = t; 51 } 52 continue; 53 } 54 for(int i = 0; i < 4; i++) { 55 int tpx = tp.first + dir[i][0]; 56 int tpy = tp.second + dir[i][1]; 57 if(tpx >= 0 && tpy >= 0 && tpx < 302 && tpy < 302 && ptime[tpx][tpy] == -1) { 58 if(t+1 < dtime[tpx][tpy]) { 59 que.push(Point(tpx, tpy)); 60 ptime[tpx][tpy] = t+1; 61 } 62 } 63 } 64 } 65 if(min != 9999999) { 66 printf("%d\n", min); 67 } 68 else { 69 puts("-1"); 70 } 71 return 0; 72 }
作題時遇到的問題:io
一開始沒有判斷使其不能回到走過的地方class
一開始t沒有加一操做,加上加一操做時的位置一開始也不對
注意到的點:
28行,33行min()的使用
注意若是無可行解要輸出-1