其中,比较关键的是对位置四个方位的判断,四个方位可以写作i-1,i+1,j-1,j+1(左,右,上,下),同时要判断四个方位有没有超出数组范围(0<=i<n&&0<=j<m)
package lanqiao;
import java.util.Scanner;
/**
* 2023/11/9
* 蓝桥549扫雷
*/
public class lanqiao549_扫雷 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
//输入数组,n为行,m为列
int n=scan.nextInt();
int m=scan.nextInt();
int[][] arr=new int[n][m];
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
arr[i][j]=scan.nextInt();
//主要判断过程
System.out.println("输出方格:");
for (int i=0;i<n;i++){//循环遍历数组
for (int j=0;j<m;j++){
if (arr[i][j]==1)//当遇到数字1,意味着此处有地雷,标记为9
System.out.print(9+" ");
else{//其他情况要判断上下左右四个方位
int ans=0;//记录四周的地雷树
for (int r=i-1;r<=i+1;r++){//左右
for (int t=j-1;t<=j+1;t++){//上下
if (r<0||r>=n||t<0||t>=m)//判断四个方向是否越界,如果越界就跳出本次循环,判断其他方向
continue;
if (arr[r][t]==1)//如果四个方向中有地雷,则答案数加1
ans++;
}
}
System.out.print(ans+" ");
}
}
System.out.println();
}
}
}
3 4
0 1 0 0
1 0 1 0
0 0 1 0
输出方格:
2 9 2 1
9 4 9 2
1 3 9 2
进程已结束,退出代码为 0