大家好,我是晴天学长,今天讲解的是一道基础题,其实用bfs有些复杂了,用逆向枚举会简单些但是也是一个复习的过程,加油!需要的小伙伴请自取哦!💪💪💪
1 )扫雷
2) .算法思路
(方法一-bfs)
扫雷()
1.接收一个nm大小的二维数组,是1的直接改成9
2.遍历矩阵,不是9的直接bfs
2.bfs
压入坐标
while
取出对头,上下左右(限制条件为该点的8个方格内获取二维矩阵内)
9直接
sum++
(方法二-遍历)
扫雷()
1.接收一个nm大小的二维数组,是1的直接改成9
2.遍历矩阵,是9的直接在周围的数中+1(注意越界问题)
3).代码示例
(方法一-bfs)
package LanQiaoTest.BFS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class 扫雷 {
//偏位移
static int[] dx = {1, -1, 0, 0, 1, -1, 1, -1};
static int[] dy = {0, 0, 1, -1, 1, 1, -1, -1};
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int[][] G = new int[n][m];
for (int i = 0; i < n; i++) {
s = in.readLine().split(" ");
for (int j = 0; j < m; j++) {
int a = Integer.parseInt(s[j]);
if (a == 1) {
a = 9;
}
G[i][j] = a;
}
}
//遍历二维数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!(G[i][j] == 9)) {
G[i][j] = bfs(n, m, i, j, G);
}
}
}
//输出数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(G[i][j] + " ");
}
System.out.println();
}
}
private static int bfs(int n, int m, int x, int y, int[][] G) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x, y});
int ans = 0;
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int a = curr[0], b = curr[1];
//正方向和45度方向
for (int i = 0; i < 8; i++) {
int newX = a + dx[i];
int newY = b + dy[i];
if (newX >= 0 && newX < n && newY >= 0 && newY < m) {
if (G[newX][newY] == 9) {
ans++;
}
}
}
}
return ans;
}
}
(方法二-遍历)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
//偏位移
static int[] dx = {1,-1,0,0,1,-1,1,-1};
static int[] dy = {0,0,1,-1,1,1,-1,-1};
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int[][] G = new int[n][m];
//接收矩阵
for (int i = 0; i < n; i++) {
s = in.readLine().split(" ");
for (int j = 0; j < m; j++) {
int a = Integer.parseInt(s[j]);
if (a==1) {
a=9;
}
G[i][j] = a;
}
}
//遍历矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (G[i][j]==9) {
for (int j2 = 0; j2 < 8; j2++) {
int newX = i + dx[j2];
int newY = j + dy[j2];
if (newX>=0&&newX<n&&newY>=0&&newY<m&&!(G[newX][newY]==9)) {
G[newX][newY]++;
}
}
}
}
}
//输出矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(G[i][j]+" ");
}
System.out.println();
}
}
}
4).总结
- bfs的基础做法
- 枚举的逆向思维
–