diff --git a/experiments/exp06/G.cpp b/experiments/exp06/G.cpp index 01c79ad47751e265964cbc6c4122c1b59cdb6aff..18134f70b0fa7522a7951874a728d678064537fb 100644 --- a/experiments/exp06/G.cpp +++ b/experiments/exp06/G.cpp @@ -1,43 +1,46 @@ -// -// Created by webturing on 2024/1/1. -// -#include - +#include +#include using namespace std; -int g[100][100]; -int n, m; //n点的个数 m边的个数 -int book[100]; -int tot = 0; -int q[100 * 100], head = 0, tail = -1; - -void bfs(int k) { - head = 0, tail = -1; - q[++tail] = k; - book[k] = 1; - while (head <= tail) { +int n; +int g[100][100], book[100]; //g是邻接矩阵,book是标记数组,标记是否访问过 +queue q; - int h = q[head++]; +void bfs(){ + /* bfs模板:(无脑套就行) + 先入队 + 后while(队列不空){ + 取队首元素,这个就是目标元素了 + 然后探索,用for探索周边最近的节点 + if剪枝判断是否符合,符合条件则放入队列 + } + + */ + q.push(0); + book[0] = 1; + while (!q.empty()) + { + int h = q.front(); + q.pop(); cout << h << " "; - for (int i = 0; i < n; i++) { - if (book[i] == 0 && g[h][i] == 1) { - q[++tail] = i; + book[h] = 1; + for (int i = 0; i < n; i++) + { + if(!book[i] && g[h][i]){ + q.push(i); book[i] = 1; } } + } - + } - -int main() { +int main(){ cin >> n; - for (int x = 0; x < n; x++) - for (int y = 0; y < n; y++) { - cin >> g[x][y]; - m += g[x][y]; + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cin >> g[i][j]; } - fill(book, book + n, 0); - bfs(0); - return 0; -} - + } + bfs(); +} \ No newline at end of file