华为机试:欢乐的周末

题目来源

题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

题目解析

思路:

  • 将人的位置和餐馆位置存储起来
  • 然后以每一个餐馆为起点,进行深度优先搜索,只有能够到达两个人的时候才进行cnt++
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <random>
#include <ctime>
#include <iterator>

using namespace std;

bool process(int currX, int currY, int targetX, int targetY, std::vector<std::vector<int>> &m){
    if(currX == targetX && currY == targetY){
        return true;
    }

    std::vector<std::vector<int>> dirs {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    for(auto d : dirs){
        int nextX = currX + d[0], nextY = currY + d[1];
        if(nextX < 0 || nextY < 0 || nextX >= m.size() || nextY >= m[0].size() || m[nextX][nextY] == 1){
            continue;
        }


        m[nextX][nextY] = 1;   // 走过的路不再走了,将它标志成障碍物
        if(process(nextX, nextY, targetX, targetY, m)){
            return true;
        }
    }

    return false;
}

int main(){
//    std::vector<std::vector<int>> matrix{
//            {2, 1, 0, 3},
//            {0, 1, 2, 1},
//            {0, 3, 0, 0},
//            {0, 0, 0, 0}
//    };

    int lenX = 0, lenY = 0;
  //  lenX = matrix.size(), lenY = matrix[0].size();
    cin >> lenX >> lenY;
    vector<vector<int>>matrix(lenX, vector<int>(lenY, 0));
    vector<vector<int>>persons;
    vector<vector<int>>targets;
    for (int i = 0; i < lenX; i++) {
        for (int j = 0; j < lenY; j++) {
            cin >> matrix[i][j];
            if(matrix[i][j] == 2) {
                persons.push_back({i, j});
            } else if(matrix[i][j] == 3) {
                targets.push_back({i, j});
            }
        }
    }

    auto xiaohua = persons[0], xiaowei = persons[1];
    int res = 0;
    for(auto target : targets){
        auto tmp = matrix;
        if(1 == process(xiaohua[0], xiaohua[1], target[0], target[1], tmp)){
            auto tmp = matrix;
            if(1 == process(xiaowei[0], xiaowei[1], target[0], target[1], tmp)){
                res++;
            }
        }
    }
    std::cout << res;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值