华为OD机试(C卷+D卷)2024真题目录(Java & c++ & python)
题目描述
在一个机房中,服务器的位置标识在 n*m 的整数矩阵网格中,1 表示单元格上有服务器,0 表示没有。如果两台服务器位于同一行或者同一列中紧邻的位置,则认为它们之间可以组成一个局域网。
请你统计机房中最大的局域网包含的服务器个数。
输入描述
第一行输入两个正整数,n和m,0<n,m<=100
之后为n*m的二维数组,代表服务器信息
输出描述
最大局域网包含的服务器个数。
用例
输入
2 2
1 0
1 1
输出
3
说明 [0][0]、[1][0]、[1][1]三台服务器相互连接,可以组成局域网
解题思路
可以用广度优先搜索(BFS)来解决。我们需要遍历整个矩阵,对于每一个发现的服务器(即矩阵中的 1),我们使用 BFS 来统计和其相连的所有服务器的数量,记录最大的局域网包含的服务器个数。
- 遍历整个矩阵,寻找每个服务器(即矩阵中的 1)。
- 对每个发现的服务器,使用 BFS 来找到所有和它直接或间接相连的服务器,并计算这些服务器的数量。
- 在 BFS 中,我们使用队列来存储需要访问的服务器,同时标记已访问的服务器,避免重复计算。
- 在遍历过程中,记录最大的局域网包含的服务器个数。
- 输出最大的局域网包含的服务器个数。
参考代码
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
// 矩阵的行数和列数
static int rows;
static int cols;
// 矩阵
static int[][] matrix;
// 四个方向的偏移量:上、下、左、右
static int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入矩阵的行数和列数
rows = sc.nextInt();
cols = sc.nextInt();
// 初始化矩阵
matrix = new int[rows][cols];
// 输入矩阵的值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
// 输出最大的连通块大小
System.out.println(findLargestConnectedComponent());
}
// 找到矩阵中最大的连通块的大小
public static int findLargestConnectedComponent() {
int maxConnectedCount = 0;
// 遍历矩阵,查找连通块
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 1) {
// 更新最大连通块的大小
maxConnectedCount = Math.max(maxConnectedCount, bfs(i, j));
}
}
}
return maxConnectedCount;
}
// 使用广度优先搜索计算连通块的大小
public static int bfs(int startX, int startY) {
Queue<int[]> queue = new LinkedList<>();
int connectedCount = 1;
matrix[startX][startY] = 0; // 标记访问过的点
// 将起始点加入队列
queue.add(new int[]{startX, startY});
// 当队列不为空时,继续搜索
while (!queue.isEmpty()) {
int[] pos = queue.poll();
int x = pos[0];
int y = pos[1];
// 遍历四个方向
for (int[] direction : directions) {
int newX = x + direction[0];
int newY = y + direction[1];
// 检查新坐标是否在矩阵范围内并且是连通的部分
if (newX >= 0 && newX < rows && newY >= 0 && newY < cols && matrix[newX][newY] == 1) {
connectedCount++;
matrix[newX][newY] = 0; // 标记新点为已访问
queue.add(new int[]{newX, newY}); // 将新点加入队列
}
}
}
return connectedCount;
}
}