大家好,我是晴天学长,扫雷也是经典中的经典,这是一个简单的bfs遍历题!💪💪💪
1 )扫雷游戏
2) .算法思路
扫雷游戏(BFS)
1.接收n,m,用快读接收
2.字符串二维数组s
3.遍历二维数组,用bfs解决
4.输出数组(保存结果数组),如果是0,且接收数组是炸弹,则输出"*"
3).代码示例
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 bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] s = bufferedReader.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
String[][] map = new String[n + 1][m + 1];
//保存答案
int[][] result = new int[n+1][m+1];
//接收数据
for (int i = 1; i <= n; i++) {
s = bufferedReader.readLine().split("");
for (int j = 1; j <= m; j++) {
map[i][j] = s[j - 1];
}
}
//遍历数据
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (!(map[i][j].equals("*"))) {
//答案
int ans = BFS(map, i, j, n, m);
result[i][j]=ans;
}
}
}
//输出数据
for (int i = 1; i <=n ; i++) {
for (int j = 1; j <=m ; j++) {
if (map[i][j].equals("*")){
System.out.print("*");
}
else {
System.out.print(result[i][j]);
}
}
System.out.println();
}
}
private static int BFS(String[][] map, int x, int y, int n, int m) {
//队列
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];
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 (map[newx][newy].equals("*")){
ans++;
}
}
}
}
return ans;
}
}
4).总结
- BFS模板