constint N = 1010; vector<int> graph[N]; bool visited[N];
voidbfs(int start){ queue<int> q; q.push(start); visited[start] = true; while (!q.empty()) { int curr = q.front(); q.pop(); cout << curr << " "; // 处理当前节点 for (int next : graph[curr]) { if (!visited[next]) { q.push(next); visited[next] = true; } } } }
intmain(){ int n, m; // n个节点,m条边 cin >> n >> m; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); // 无向图需要双向添加 } bfs(1); // 从节点1开始BFS return0; }
intmain(){ int n, m, start, end; cin >> n >> m >> start >> end; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } bfs(start, end); if (visited[end]) { cout << "Path found: "; printPath(end); } else { cout << "No path found."; } return0; }
constint N = 100; int grid[N][N]; bool visited[N][N]; int dist[N][N]; // 记录距离
// 四个方向:上、右、下、左 int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1};
voidbfs(int startX, int startY, int n, int m){ queue<pair<int, int>> q; q.push({startX, startY}); visited[startX][startY] = true; dist[startX][startY] = 0; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); // 尝试四个方向 for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; // 边界检查和有效性检查 if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny] && grid[nx][ny] != 1) { // 1表示障碍 q.push({nx, ny}); visited[nx][ny] = true; dist[nx][ny] = dist[x][y] + 1; } } } }
intmain(){ int n, m; cin >> n >> m; // 输入网格 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> grid[i][j]; } } int startX, startY, endX, endY; cin >> startX >> startY >> endX >> endY; bfs(startX, startY, n, m); if (visited[endX][endY]) { cout << "最短距离: " << dist[endX][endY] << endl; } else { cout << "无法到达终点" << endl; } return0; }