华为OD 机试题(Java实现)
小镇做题家,做题记录,微信:yatesKumi
题目描述
给定一个N行M列的二维矩阵,矩阵中每个位置的数字取值为0或1。矩阵示例如:
1100
0001
0011
1111
现需要将矩阵中所有的1进行反转为0,规则如下:
- 当点击一个1时,该1便被反转为0,同时相邻的上、下、左、右,以及左上、左下、右上、右下8个方向的1(如果存在1)均会自动反转为0;
2)进一步地,一个位置上的1被反转为0时,与其相邻的8个方向的1(如果存在1)均会自动反转为0;
按照上述规则示例中的矩阵只最少需要点击2次后,所有值均为0。请问,给定一个矩阵,最少需要点击几次后,所有数字均为0?
输入描述
第一行输入两个数字N,M,分别表示二维矩阵的行数,列数,并用空格隔开
之后输入N行,每行M个数字,并用空格隔开
输出描述
最少需要点击几次后,矩阵中所有数字均为0
import java.util.*;
public class Main {
private static final int[][] directions = {
{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int clicks = countClicks(matrix);
System.out.println(clicks);
}
private static int countClicks(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int clicks = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 1) {
clicks++;
matrix[i][j] = 0;
queue.offer(new int[] {i, j});
while (!queue.isEmpty()) {
int[] curr = queue.poll();
for (int[] direction : directions) {
int nextRow = curr[0] + direction[0];
int nextCol = curr[1] + direction[1];
if (nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < m && matrix[nextRow][nextCol] == 1) {
matrix[nextRow][nextCol] = 0;
queue.offer(new int[] {nextRow, nextCol});
}
}
}
}
}
}
return clicks;
}
}
算法的核心是广度优先搜索,我们从每个值为1的位置出发,将所有连通的1全部标记为0,并计数器加1。具体来说,我们维护一个队列,将第一个位置的坐标加入队列,然后对队列中的每个位置进行扩展,如果邻居是1,则将其标记为0,并加入队列。一旦队列为空,说明所有连通的1已经标记为0,此时我们更新计数器,并重复上述步骤,直到所有位置都被标记为0。
时间复杂度:O(nm),其中n是矩阵的行数,m是矩阵的列数。