题目:
分析:
代码:
import java.util.Scanner;
public class Main {
/*
* 思路:
测试数据
5 5
00010
00010
01001
10001
01000
正常输出:2
* */
static int[] row;//标记行列是否已访问
static int[] col;
static int n;//行
static int m;//列
static int cnt=0;//记录最少引用的炸弹数
public static void main(String[] args){
//1.输出相关值
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//n行
int m = sc.nextInt();//m列
char[][] g = new char[n][];
row = new int[n];
col = new int[m];
for(int i=0;i<n;i++) {
g[i] = sc.next().toCharArray();
}//for
//2.进行遍历
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(g[i][j]=='1' && col[j]==0 && row[i]==0) {//该位置的炸弹没有引爆
cnt++;
dfs(i,j,g);//引爆该炸弹
for(int k=0;k<n;k++) {//打印每次引爆炸弹后的状态
for(int p=0;p<m;p++) {
System.out.print(g[k][p]);
}
System.out.println();
}
System.out.println();
}
}
}
//3.输出结果
System.out.println(cnt);
}
//3.从位置g[x][y]开始引爆炸弹,将引爆的炸弹标记为0,并且将其所在行列的炸弹引爆
//注意:不要直接用n和m,使用g.length 和 g[0].length
private static void dfs(int x, int y,char[][] g) {
g[x][y] = '0';//注意:先将当前的炸弹引爆,设置为0!
if(row[x]==0) {//第x行没有访问过(即没有引爆过),则引爆该行的炸弹
row[x] = 1;
for(int i=0;i<g[0].length;i++) {
if(g[x][i]=='1'&&col[i]==0) {//有未被引爆的炸弹
dfs(x,i,g);
}
}
}//if
if(col[y]==0) {//第y列没有访问过(即没有引爆过),则引爆该行的炸弹
col[y] = 1;
for(int i=0;i<g.length;i++) {
if(g[i][y]=='1' && row[i]==0) {//有未被引爆的炸弹
dfs(i,y,g);
}
}
}//if
}
}