1. 程式人生 > >深搜遞歸回來時候,取消與不取消標記的探討

深搜遞歸回來時候,取消與不取消標記的探討

不可 ack 使用 等於 for else secure n) continue

 1 #define _CRT_SECURE_NO_WARNINGS  
 2 #include <stdio.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <stdlib.h>
 6 #include <vector>
 7 #include <map>
 8 #include <queue>
 9 #include <string>
10 #include <iostream>
11 #include <ctype.h>
12
#include <string.h> 13 #include <set> 14 #include <stack> 15 #include<functional> 16 using namespace std; 17 #define Size 22 18 #define maxn 1<<30 19 #define minn 1e-6 20 char a[Size][Size]; 21 int mark[Size][Size]; 22 int stx, sty; 23 int width, len; 24 int ans; 25 int
go[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0 }; 26 void solve(int x,int y,int step){ 27 if (x<1 || y<1 || x>len || y>width||a[x][y]==#){ 28 if (ans < step){ 29 cout << step << endl; 30 ans = step; 31 } 32 } 33 else { 34 for
(int i = 0; i < 4; i++){ 35 int tx = x + go[i][0]; 36 int ty = y + go[i][1]; 37 if (mark[tx][ty]) continue; 38 if (a[tx][ty] == .) step++; 39 mark[tx][ty] = 1; 40 solve(tx, ty,step); 41 mark[tx][ty] = 0;//所以不標記的情況一般是在重復使用字母,數字的時候,解空間很小的情況下,如果要搜索地圖的時候,不標記,時間太多不可接受 42 /* 43 雖然可能搜索到最終答案但是,解空間是非常大的如果不標記的話那麽,因為除過此來到的路其他路都要再走一次,解空間非常大非常大可能是3^64 44         因為其等於計算了從起點到地圖上任意一點的所有路徑,假設每次有三個選擇,那麽在一個8*8的地圖上那麽總共要計算的次數是64*3^64,天文數字 而不取消標記的情況是計算,即深搜的模板方案,是計算最佳方案的即為,計算最快到達i,j點的路徑,要計算最慢到達ij的路徑就不行了,此題等效計算最長路徑 45 */ 46 if (a[tx][ty] == .) step--; 47 } 48 } 49 } 50 51 int main(){ 52 53 while (cin >> width >> len){ 54 int num = 0; 55 for (int i = 1; i <= len; i++) 56 for (int j = 1; j <= width; j++){ 57 mark[i][j] = 0; 58 cin >> a[i][j]; 59 if (a[i][j] == @) stx = i, sty = j; 60 } 61 mark[stx][sty] = 1; 62 ans = 0; 63 solve(stx, sty,1);//將要探索stx,sty,以及走了0步了 64 } 65 return 0; 66 }

深搜遞歸回來時候,取消與不取消標記的探討