廣度優先搜尋

2021-08-13 06:37:19 字數 1599 閱讀 9413

以uoj上的騎士遊歷為例

傳送門

struct note  que[2501];

que[tail].x = 1; //x座標

que[tail].y = 1; //y座標

que[tail].s = 0; //記錄步數

tail++;

b[1][1] = 1; //標記陣列

while(head < tail)

if(!b[tx][ty])

if(tx == n && ty == m)

}if(judge)

head++; //頭指標一定要++

}

令我印象深刻的一道廣搜。

p1141 01迷宮

第一次,沒有反應過來,有100000組詢問,而我第一次每次詢問都去廣搜了一遍,結果70分。

第二次,請教了學長,發現從任意一點出發,與從那一點出發能到達的所有點中的任意一點出發,能到達的格數是一樣的,據說這叫連通塊。所以只用廣搜一次,從每個未被訪問過的點出發,直到遍歷完全圖。據說這叫「預處理」。**沒有體現物件導向的原則……

#include

#include

#include

#include

#include

#include

using

namespace

std;

struct node

} que[1000000];

intmap[1001][1001],b[1001][1001];

int n,m;

int read_in()

while (ch >= '0' && ch <= '9')

if (minus) a = -a;

return a;

}void printout(int x) while (x);

if (minus) buffer[length++] = '-';

do while (length);

putchar('\n');

}void bfs(int start_x,int start_y) ,,,};

int head = 0,tail = 0;

b[start_x][start_y] = 1;

que[tail].x = start_x;

que[tail].y = start_y;

que[tail].s = map[start_x][start_y];

tail++;

int tx,ty;

while(head < tail)

if(!b[tx][ty] && map[tx][ty] + que[head].s == 1)

}head++;

}for(int i = 0; iint main()

}for(int i = 1; i<=n; i++)

if(!b[i][j]) }}

for(int i = 1; i<=m; i++)

return

0;}

搜尋 廣度優先搜尋

廣度優先搜尋一層一層地進行遍歷,每層遍歷都是以上一層遍歷的結果作為起點,遍歷乙個距離能訪問到的所有節點。需要注意的是,遍歷過的節點不能再次被遍歷。class solution,int shortestpathbinarymatrix vectorint grid length return 1 cl...

廣度優先搜尋

include include include include using namespace std struct node 圖頂點結構定義 typedef struct node graph 圖形的結構新型態 struct node head 9 圖形頂點陣列 int visited 9 遍歷標...

廣度優先搜尋

廣度優先搜尋詳解 1.也稱寬度優先搜尋,顧名思義,就是將一棵樹一層一層往下搜。演算法首先搜尋和s距離為k的所有頂點,然後再去搜尋和s距離為k l的其他頂點。bfs是一種完備策略,即只要問題有解,它就一定可以找到解。並且,廣度優先搜尋找到的解,還一定是路徑最短的解。但是它盲目性較大,尤其是當目標節點距...