给定一个N行M列的二维矩阵,矩阵中每个位置的数字取值为0或1。矩阵示例如:
1100
0001
0011
1111
现需要将矩阵中所有的1进行反转为0,规则如下:
1) 当点击一个1时,该1便被反转为0,同时相邻的上、下、左、右,以及左上、左下、右上、右下8 个方向的1(如果存在1)均会自动反转为0;
2)进一步地,一个位置上的1被反转为0时,与其相邻的8个方向的1(如果存在1)均会自动反转为0;
按照上述规则示例中的矩阵只最少需要点击2次后,所有值均为0。请问,给定一个矩阵,最少需要点击几次后,所有数字均为0?
输入描述:
第一行为两个整数N和M,分别代表矩阵的行数和列数。
接下来的N行为矩阵的初始值,每行M个整数
输出描述:
输出一个整数,表示最少需要点击的次数
示例1:
输入:
3 3
1 0 1
0 1 0
1 0 1
输出:
1
示例2:
输入:
4 4
1 1 0 0
0 0 0 1
0 0 1 1
1 1 1 1
输出:
2
Java 代码
import java.util.Scanner;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigInteger;
class Main {
public static void main(String[] args) {
// 处理输入
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] matrix = new int[n][m];
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
matrix[x][y] = in.nextInt();
}
}
int result = 0;
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
//从任意一个位置的1开始遍历
if (matrix[x][y] == 1) {
result++;
bfs(n, m, matrix, x, y);
}
}
}
System.out.println(result);
}
public static void bfs(int n, int m, int[][] matrix, int x, int y) {
matrix[x][y] = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < n && j >= 0 && j < m &&
matrix[i][j] == 1) {
bfs(n, m, matrix, i, j);
}
}
}
}
}
Python代码
import functools
import sys
directions = [[0, 1], [0, -1], [1, 0], [-1, 0],[1, 1], [1, -1], [-1, -1], [-1, 1]]
def bfs(n, m, matrix, flipped):
global directions
if (len(flipped) ==0):
return;
pos = flipped.pop(0)
for d in directions:
newX = pos[0] + d[0]
newY = pos[1] + d[1]
if (newX >= 0 and newX < n and
newY >= 0 and newY < m and
matrix[newX][newY] == 1):
matrix[newX][newY] = 0
flipped.append([newX, newY])
bfs(n, m, matrix, flipped)
# 处理输入
params = [int(x) for x in input().split(" ")]
n =params[0]
m = params[1]
matrix = []
for i in range(n):
matrix.append([int(x) for x in input().split(" ")])
#起点可以是每一个位置
result = 0;
for i in range(n):
for j in range(m):
if (matrix[i][j] == 1):
result += 1
flipped = []
flipped.append([i,j])
bfs(n, m, matrix, flipped)
print(result)
JS代码
class UF {
constructor(n) {
this.count = n
this.item = new Array(n)
for(let i=0;i= 0 &&new_x < n &&new_y >= 0 &&new_y < m &&matrix[new_x][new_y] == 1) {
uf.union_connect(i * m + j, new_x * m + new_y);
}
}
}
}
console.log(uf.count)
}
main([[1, 1, 0, 0],[0, 0 ,0, 1],[0, 0 ,1, 1],[1 ,1, 1, 1]])