hdoj1242(dfs 剪枝 解法)
生活随笔
收集整理的這篇文章主要介紹了
hdoj1242(dfs 剪枝 解法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:拯救行動,天使r有多個朋友a(friends,在這里被坑了幾次,沒看清題意),天使被關在牢房里,等著朋友來拯救,求拯救天使的最短距離。
解法:如果不剪枝,200*200的地圖會超時,可以以天使為起點進行dfs,記錄到達map[x][y]的最小值、到達每個a的最小值。
#include <iostream> #include <cstring> #include <cstdio> using namespace std;const int M = 205; char map[M][M]; int minL[M][M]; //記錄到達x,y的最小值,如果再次到達大于最小值,則說明沒有必要走下去了 int minLtoR; int visited[M][M]; int n,m; //int step; int dire[4][2] = {{-1,0},{0,-1},{1,0},{0,1}}; void dfs(int v1,int v2,int step) {if(map[v1][v2] == 'a'){if (step < minLtoR){minLtoR = step; //記錄到達a的最小值 }else return;}for (int i = 0; i < 4; i++){int x = v1+dire[i][0];int y = v2+dire[i][1];if (!visited[x][y] && map[x][y]!='#' && x < n && x >= 0 && y < m && y >= 0){if (step+1 > minL[x][y])continue; //沒有必要再走下去了else minL[x][y] = step+1; //更新最小值visited[x][y] = 1;if (map[x][y] == 'x')dfs(x,y,step+2);else dfs(x,y,step+1);visited[x][y] = 0;}} } int main() {while (cin >> n >> m){int step = 0;minLtoR = 1000000;int x,y;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){cin >> map[i][j];visited[i][j] = 0;minL[i][j] = 1000000;if (map[i][j] == 'r'){x = i;y = j;}}}dfs(x,y,step);if (minLtoR == 1000000)cout << "Poor ANGEL has to stay in the prison all his life.\n";else cout << minLtoR << endl;}return 0; }博客原創,轉載請說明出處。
轉載于:https://www.cnblogs.com/ediszhao/p/4741825.html
總結
以上是生活随笔為你收集整理的hdoj1242(dfs 剪枝 解法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]提示错误 package java
- 下一篇: SVN库迁移