LeetCode 每日一题 2022 0414— 模拟 和 多元BFS

第一题 模拟

在这里插入图片描述
https://leetcode-cn.com/problems/richest-customer-wealth/

  • 思路
  1. 遍历每一行,求和
  2. 更新最大值
  3. 返回
	int maximumWealth(vector<vector<int>>& accounts) {
		int ret = INT_MIN;
		for (auto &person : accounts) {
			int sum = 0;
			for (int n : person) {
				sum += n;
			}
			ret = max(ret, sum);
		}
		return ret;
	}

第二题 多元BFS(hot 200)

在这里插入图片描述
https://leetcode-cn.com/problems/walls-and-gates/

  • 思路
  1. 从门的位置作为起点,进行搜索
  2. 因为门的位置很多,我们以所有门的位置为起点
  3. 依次进入队列搜索,搜索相邻的四个位置,值为当前值+1
  4. 仅对INT_MAX的位置进行搜索,其他位置不是已经搜索过就是墙

在这里插入图片描述

	void wallsAndGates(vector<vector<int>>& rooms) {
		if (rooms.empty())
			return;

		int m = rooms.size(), n = rooms[0].size();
		queue<pair<int, int>> cur;

		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				if (rooms[i][j] == 0) {
					cur.push({i, j});
				}
			}
		}

		int dirs[][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
		while (!cur.empty()) {
			
			int x = cur.front().first, y = cur.front().second;
			cur.pop();

			for (int i = 0; i < 4; ++i) {
				int nextX = x + dirs[i][0], nextY = y + dirs[i][1];

				if(nextX >= 0 && nextY >= 0 && nextX < m && nextY < n){
					if (rooms[nextX][nextY] == INT_MAX) {
						rooms[nextX][nextY] = rooms[x][y] + 1;
						cur.push({nextX, nextY});
					}
				}
			}
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值