Detonated a bomb (dfs solution)

Problem Description

On a grid map of n × m, the bomb placed on a certain box. Manually detonated a bomb after bomb on all the rows and columns where the bomb would detonate the bomb, but the bomb detonated bomb detonated other, so the chain continues.

Now in order to detonate a bomb on all maps, some of which need to manually detonate the bomb, in order to minimize the degree of risk, please calculate how many bombs can be detonated manually least all the bombs detonated on the map.

Input Format

A first transmission line of two integers n, m; n, m, separated by a space.
Next n lines, a length of each line of input string m, showing the map information.
0 means no bombs, 1 bomb.
Data convention:
for 60% of data: 1 <= n, m < = 100;
100% data: 1 <= n, m < = 1000;
larger than the data, input cin not recommended.

Output Format

Output An integer that represents the minimum number required to manually detonate the bomb.

Sample input
5 5
00010
00010
01001
10001
01000
Sample Output
2

Sample code:

/**
    该题说要算出手动引爆炸弹的最小个数
    其实只要中规中矩从mp[0][0]按正常顺序遍历第一个炸弹开始引爆就可以了(想多的话还会特地找这个最小值,其实大可不必) 
    原因:
        一个炸弹引爆会牵扯到一行炸弹和一列炸弹,被牵扯到的炸弹也会这样牵扯下去,产生连锁效应 
*/ 

#include<cstdio>
char mp[1005][1005];    //存储地图信息
int n, m;    //存储行列的值 
int cnt;     //用来记录手动引爆的次数 
bool vx[1005], vy[1005];    //标记行列有没有被引爆(用来避免重复引爆) 

void dfs(int x, int y ) {
    //printf("(%d,%d)\n",x,y);
    
    mp[x][y] = '0'; //被引爆的炸弹就置为0 避免重复引爆 
    
    if(!vx[x]) {    // x 行没有被引爆则进行引爆 
    
        vx[x] = true;   //x 行标记为 已引爆状态   
        
        for(int i = 0; i < m; i ++) {   //在 x 行上寻找其他的炸弹 
            if(mp[x][i] == '1') {   //找到炸弹则继续引爆该炸弹 
                dfs(x, i);  
            }
        }
    }
    if(!vy[y]) {    // y 列没有被引爆则进行引爆 
        
        vy[y] = true;   //y 行列标记为 已引爆状态 
        
        for(int i = 0; i < n; i ++) {    //在 y 列上寻找其他的炸弹 
            if(mp[i][y] == '1') {    //找到炸弹则继续引爆该炸弹 
                dfs(i, y);
            }
        }
    }
} 

int main() {
    scanf("%d%d",&n,&m);
    
    for (int i = 0; i < n; i ++) {
        scanf("%s",&mp[i]);
    }
    
    for (int i = 0; i < n; i ++) {
        for (int j = 0; j < m; j ++) {
            
            if (mp[i][j] == '1') {  //找到一个炸弹就开始手动引爆 
                cnt ++; //手动引爆次数 +1 
                dfs(i, j);  //深搜传入炸弹的坐标 
            }
        }
    }
    printf("%d\n", cnt);
    return 0;
} 

Guess you like

Origin www.cnblogs.com/zhixiangshu/p/12305880.html