BFS,DFS 典型题目总结

这篇博客介绍了两种图论算法——BFS(广度优先搜索)和DFS(深度优先搜索)在解决最短路径问题和计算连通块个数及最大面积问题上的应用。通过示例题目‘仙岛求药’和‘最大岛屿’,展示了如何使用这两种算法来寻找迷宫中的最短路径以及在二维矩阵中找到最大岛屿的面积。BFS适用于寻找最短路径,而DFS则用于查找连通组件并计算其数量和面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.   最短路径+判断无解:

例题: ybt 1251:仙岛求药

BFS:

#include <bits/stdc++.h>
using namespace std;
 
const int N = 105;
 
constexpr int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
 
struct node { int x, y, step; } S, E;
 
int m, n;
char a[N][N];
bool vis[N][N];
 
inline bool input() {
	scanf("%d%d", &m, &n);
	if (m == 0 && n == 0) return false;
	for (int i = 1; i <= m; i++) {
		scanf("%s", a[i] + 1);
		for (int j = 1; j <= n; j++) {
			if(a[i][j] == '@') S = {i, j};
			if(a[i][j] == '*') E = {i, j};
		}
	}
	memset(vis, false, sizeof(vis));
	return true;
}
 
inline void bfs() {
	auto isValid = [](int x, int y) {
		return (1 <= x && x <= m && 1 <= y && y <= n && a[x][y] != '#' && !vis[x][y]);
	};
	queue<node> q; q.push(S);
 
	while (!q.empty()) {
		node u = q.front(); q.pop();
 
		for(int i = 0; i < 4; i++) {
			int _x = u.x + dx[i], _y = u.y + dy[i];
 
			if (!isValid(_x, _y)) continue;
			
			if (_x == E.x && _y == E.y) {
				printf("%d\n", u.step + 1);
				return;
			}
			q.push({_x, _y, u.step + 1});
			vis[_x][_y] = true;
		}
	}
	printf("-1\n");
}
 
signed main() {
	while (input()) bfs();
	return 0;
}

DFS:

#include <bits/stdc++.h>
using namespace std;
 
const int N = 105;
 
constexpr int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
 
int m, n, step[N][N];
char a[N][N];
bool hasAns;
 
int st_x, st_y, ed_x, ed_y;
 
inline bool input() {
	scanf("%d%d", &m, &n);
	if (m == 0 && n == 0) return false;
	for (int i = 1; i <= m; i++) {
		scanf("%s", a[i] + 1);
		for (int j = 1; j <= n; j++) {
			if(a[i][j] == '@') st_x = i, st_y = j;
			if(a[i][j] == '*') ed_x = i, ed_y = j;
		}
	}
	memset(step, 0x3f, sizeof(step)); step[st_x][st_y] = 0;
	return true;
}
 
inline bool isValid(int x, int y) {
	return (1 <= x && x <= m && 1 <= y && y <= n && a[x][y] != '#');
};
 
inline void dfs(int x, int y) {
	if (a[x][y] == '*') {
		hasAns = true;
		return;
	}
	for(int i = 0; i < 4; i++) {
		int _x = x + dx[i], _y = y + dy[i];
 
		if (!isValid(_x, _y)) continue;
		if (step[_x][_y] <= step[x][y] + 1) continue;
 
		step[_x][_y] = step[x][y] + 1;
		dfs(_x, _y);
	}
}
 
signed main() {
	while (input()) {
		hasAns = false;
		dfs(st_x, st_y);
		if (hasAns) printf("%d\n", step[ed_x][ed_y]);
		else printf("-1\n");
	}
	return 0;
}

2.   连通块个数+最大面积:

例题: 计蒜客 T1405 最大岛屿

BFS:

#include <bits/stdc++.h>
using namespace std;

const int N = 505;

constexpr int dx[]= {0, 0, 1, -1, 1, -1, 1, -1};
constexpr int dy[]= {1, -1, 0, 0, 1, -1, -1, 1};
 
struct node { int x, y; };

int m, n, t;
char a[N][N];
bool vis[N][N];

int cnt, ans, now;
 
inline void bfs(int x,int y) {
    auto isValid = [](int x, int y) {
        return (1 <= x && x <= m && 1 <= y && y <= n && a[x][y] != '0' && !vis[x][y]);
    };
    
	queue<node> q; q.push({x, y});
 
	while (!q.empty()) {
		node u = q.front(); q.pop();
 
		for (int i = 0; i < 8; i++) {
            int _x = u.x + dx[i], _y = u.y + dy[i];
			if (!isValid(_x, _y)) continue;
            vis[_x][_y] = true;
			now++;
			q.push({_x, _y});
		}
	}
}
 
inline void input() {
	scanf("%d%d%d", &m, &n, &t);
	for (int i = 1; i <= m; i++)
		for (int j = 1; j <= n; j++) {
			do {
				a[i][j] = getchar();
			} while (a[i][j] != '0' && a[i][j] != '1');
		}
}
 
inline void solve() {
	for (int i = 1; i <= m; i++) {
		for (int j = 1; j <= n; j++) {
			if (a[i][j] == '0' || vis[i][j]) continue;
            vis[i][j] = true;
			now = 1;
			bfs(i, j);
            ans = max(ans, now);
			cnt++;
		}
	}
	printf("%d %d\n", cnt, ans * t);
}
 
signed main() {
	input();
	solve();
	return 0;
}

DFS:

#include <bits/stdc++.h>
using namespace std;

const int N = 505;

constexpr int dx[]= {0, 0, 1, -1, 1, -1, 1, -1};
constexpr int dy[]= {1, -1, 0, 0, 1, -1, -1, 1};
 
int m, n, t;
char a[N][N];
bool vis[N][N];
 
int cnt, ans, now;
 
inline void input() {
	scanf("%d%d%d", &m, &n, &t);
	for (int i = 1; i <= m; i++) {
		for (int j = 1; j <= n; j++) {
			do {
				a[i][j] = getchar();
			} while (a[i][j] != '0' && a[i][j] != '1');
		}
	}
}
 
inline bool isValid (int x, int y) {
    return (1 <= x && x <= m && 1 <= y && y <= n && a[x][y] != '0' && !vis[x][y]);
}

inline void dfs(int x,int y) {
	for (int i = 0; i < 8; i++) {
        int _x = x + dx[i], _y = y + dy[i];
		if (!isValid(_x, _y)) continue;
        vis[_x][_y] = true;
        now++;
		dfs(_x,_y);
	}
}
 
inline void solve() {
	for (int i = 1; i <= m; i++) {
		for (int j = 1; j <= n; j++) {
			if (a[i][j] == '0' || vis[i][j]) continue;
            vis[i][j] = true;
			now = 1;
			dfs(i, j);
            ans = max(ans, now);
			cnt++;
		}
	}
	printf("%d %d\n", cnt, ans * t);
}
 
signed main() {
	input();
	solve();
	return 0;
}

### Java矩阵上BFSDFS的实现 #### 广度优先搜索 (BFS) 广度优先搜索是一种逐层遍历的方式,通常借助队列来实现。以下是基于矩阵的BFS实现: ```java import java.util.LinkedList; import java.util.Queue; public class BFS { public void bfsTraversing(int[][] matrix, boolean[] visited, int startNode) { Queue<Integer> queue = new LinkedList<>(); queue.add(startNode); visited[startNode] = true; while (!queue.isEmpty()) { int currentNode = queue.poll(); System.out.print(currentNode + " "); for (int i = 0; i < matrix.length; i++) { if (matrix[currentNode][i] == 1 && !visited[i]) { queue.add(i); visited[i] = true; } } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; BFS bfs = new BFS(); bfs.bfsTraversing(adjacencyMatrix, visited, 0); // 输出节点访问顺序 } } ``` 上述代码展示了如何通过邻接矩阵表示图并执行BFS操作[^1]。 --- #### 深度优先搜索 (DFS) 深度优先搜索采用递归方式或栈结构完成遍历过程。下面是基于矩阵的DFS实现: ```java public class DFS { public void dfsTraversing(int node, int[][] graph, boolean[] visited) { visited[node] = true; System.out.print(node + " "); for (int i = 0; i < graph.length; i++) { if (graph[node][i] == 1 && !visited[i]) { dfsTraversing(i, graph, visited); } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; DFS dfs = new DFS(); dfs.dfsTraversing(0, adjacencyMatrix, visited); // 输出节点访问顺序 } } ``` 此代码片段实现了利用递归方式进行DFS的操作[^3]。 --- 对于LeetCode中的图像渲染问题,可以结合BFS/DFS解决二维数组的相关题目。例如给定初始坐标 `(sr, sc)` 新颜色 `newColor`,可以通过修改像素值达到渲染效果[^2]。 ```java class Solution { private final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; public int[][] floodFill(int[][] image, int sr, int sc, int color) { if (image[sr][sc] == color) return image; fill(image, sr, sc, image[sr][sc], color); return image; } private void fill(int[][] image, int r, int c, int oldColor, int newColor) { if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || image[r][c] != oldColor) return; image[r][c] = newColor; for (int[] dir : directions) { fill(image, r + dir[0], c + dir[1], oldColor, newColor); } } } ``` 以上代码展示了一个典型DFS应用案例——填充指定区域的颜色。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值