华为OD机试 - 寻找最大价值的矿堆 - 矩阵,通过栈优化(Python/JS/C/C++ 2025 A卷 200分)

在这里插入图片描述

华为OD机试 2025A卷题库疯狂收录中,刷题点这里

专栏导读

本专栏收录于《华为OD机试真题(Python/JS/C/C++)》

刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。

一、题目描述

给你一个由’0’(空地)、‘1’(银矿)、‘2’(金矿)组成的地图,矿堆只能由上下左右相邻的金矿或银矿连接形成。超出地图范围可以认为是空地。
假设银矿价值1,金矿价值2,请你找出地图中最大价值的矿堆并输出该矿堆的价值。

二、输入描述

地图元素信息如下:

22220
00000
00000
11111

  • 地图范围最大 300*300
  • 0 <=地图元素 <= 2

三、输出描述

矿堆的最大价值

四、测试用例

测试用例1:

1、输入

3
012
210
012

2、输出

9

测试用例2:

1、输入

5
00000
01210
01210
01210
00000

2、输出

12

五、解题思路

深度优先搜索(DFS):遍历地图中的每个矿堆,计算其连通部分的总价值。通过DFS,可以有效地找到所有相连的矿堆,并计算其总价值。

标记访问:为了避免重复计算,将已访问的矿堆标记为0(即空地)。

记录最大值:在遍历过程中,实时更新当前找到的最大矿堆价值。

六、Python算法源码

# Python 版本
import sys
from collections import deque

def main():
    # 读取输入
    N = int(sys.stdin.readline())
    lines = []
    for _ in range(N):
        line = sys.stdin.readline().strip()
        lines.append(line)
    
    rows = len(lines)
    cols = len(lines[0])
    # 构建地图矩阵
    map_matrix = [[int(ch) for ch in line] for line in lines]
    
    # 定义四个方向的偏移量
    offsets = [(-1,0), (1,0), (0,-1), (0,1)]
    
    max_val = 0
    
    for i in range(rows):
        for j in range(cols):
            if map_matrix[i][j] > 0:
                stack = deque()
                stack.append((i, j))
                sum_val = 0
                while stack:
                    x, y = stack.pop()
                    if map_matrix[x][y] == 0:
                        continue
                    sum_val += map_matrix[x][y]
                    map_matrix[x][y] = 0
                    for dx, dy in offsets:
                        new_x = x + dx
                        new_y = y + dy
                        if 0 <= new_x < rows and 0 <= new_y < cols and map_matrix[new_x][new_y] > 0:
                            stack.append((new_x, new_y))
                max_val = max(max_val, sum_val)
    
    print(max_val)

if __name__ == "__main__":
    main()

七、JavaScript算法源码

// JavaScript 版本
const readline = require('readline');

function main() {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    let input = [];
    rl.on('line', (line) => {
        input.push(line);
    });

    rl.on('close', () => {
        const N = parseInt(input[0]);
        const lines = input.slice(1, N+1);
        const rows = lines.length;
        const cols = lines[0].length;
        // 构建地图矩阵
        let map = Array.from({length: rows}, () => Array(cols).fill(0));
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                map[i][j] = parseInt(lines[i][j]);
            }
        }

        // 定义四个方向的偏移量
        const offsets = [[-1,0], [1,0], [0,-1], [0,1]];

        let maxVal = 0;

        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                if (map[i][j] > 0) {
                    let stack = [];
                    stack.push([i, j]);
                    let sum = 0;
                    while (stack.length > 0) {
                        let [x, y] = stack.pop();
                        if (map[x][y] === 0) continue;
                        sum += map[x][y];
                        map[x][y] = 0;
                        for (let [dx, dy] of offsets) {
                            let newX = x + dx;
                            let newY = y + dy;
                            if (newX >=0 && newX < rows && newY >=0 && newY < cols && map[newX][newY] > 0) {
                                stack.push([newX, newY]);
                            }
                        }
                    }
                    if (sum > maxVal) {
                        maxVal = sum;
                    }
                }
            }
        }

        console.log(maxVal);
    });
}

main();

八、C算法源码

// C 语言版本
#include <stdio.h>
#include <stdlib.h>

#define MAX 300

int map_matrix[MAX][MAX];
int rows, cols;
int offsets[4][2] = { {-1,0}, {1,0}, {0,-1}, {0,1} };

// 栈结构
typedef struct {
    int x;
    int y;
} StackNode;

typedef struct {
    StackNode data[MAX * MAX];
    int top;
} Stack;

void initStack(Stack *s) {
    s->top = -1;
}

int isEmpty(Stack *s) {
    return s->top == -1;
}

void push(Stack *s, int x, int y) {
    if (s->top < MAX * MAX -1) {
        s->data[++(s->top)].x = x;
        s->data[s->top].y = y;
    }
}

StackNode pop(Stack *s) {
    return s->data[(s->top)--];
}

int main(){
    int N;
    scanf("%d", &N);
    char line[MAX+1];
    for(int i=0;i<N;i++){
        scanf("%s", line);
        for(int j=0; j<strlen(line); j++){
            map_matrix[i][j] = line[j] - '0';
        }
    }
    rows = N;
    cols = strlen(line);
    int maxVal = 0;
    Stack stack;
    initStack(&stack);
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            if(map_matrix[i][j] > 0){
                push(&stack, i, j);
                int sum = 0;
                while(!isEmpty(&stack)){
                    StackNode node = pop(&stack);
                    int x = node.x;
                    int y = node.y;
                    if(map_matrix[x][y] == 0) continue;
                    sum += map_matrix[x][y];
                    map_matrix[x][y] = 0;
                    for(int k=0; k<4; k++){
                        int newX = x + offsets[k][0];
                        int newY = y + offsets[k][1];
                        if(newX >=0 && newX < rows && newY >=0 && newY < cols && map_matrix[newX][newY] >0){
                            push(&stack, newX, newY);
                        }
                    }
                }
                if(sum > maxVal){
                    maxVal = sum;
                }
            }
        }
    }
    printf("%d\n", maxVal);
    return 0;
}

九、C++算法源码

// C++ 版本
#include <bits/stdc++.h>
using namespace std;

int main(){
    int N;
    cin >> N;
    vector<string> lines(N);
    for(int i=0;i<N;i++) cin >> lines[i];
    int rows = N;
    int cols = lines[0].size();
    // 构建地图矩阵
    vector<vector<int>> map_matrix(rows, vector<int>(cols, 0));
    for(int i=0;i<rows;i++) {
        for(int j=0;j<cols;j++) {
            map_matrix[i][j] = lines[i][j] - '0';
        }
    }
    // 定义四个方向的偏移量
    vector<pair<int, int>> offsets = { {-1,0}, {1,0}, {0,-1}, {0,1} };
    int maxVal = 0;
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            if(map_matrix[i][j] > 0){
                stack<pair<int, int>> s;
                s.push({i, j});
                int sum = 0;
                while(!s.empty()){
                    pair<int, int> pos = s.top(); s.pop();
                    int x = pos.first, y = pos.second;
                    if(map_matrix[x][y] == 0) continue;
                    sum += map_matrix[x][y];
                    map_matrix[x][y] = 0;
                    for(auto &offset : offsets){
                        int newX = x + offset.first;
                        int newY = y + offset.second;
                        if(newX >=0 && newX < rows && newY >=0 && newY < cols && map_matrix[newX][newY] >0){
                            s.push({newX, newY});
                        }
                    }
                }
                maxVal = max(maxVal, sum);
            }
        }
    }
    cout << maxVal << endl;
    return 0;
}


🏆下一篇:华为OD机试真题 - 简易内存池(Python/JS/C/C++ 2025 A卷 200分)

🏆本文收录于,华为OD机试真题(Python/JS/C/C++)

刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哪 吒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值