1970. 你能穿过矩阵的最后一天

1970. 你能穿过矩阵的最后一天


题目链接:1970. 你能穿过矩阵的最后一天

代码如下:

cpp 复制代码
//参考链接:https://leetcode.cn/problems/last-day-where-you-can-still-cross/solutions/936629/dao-xu-bing-cha-ji-by-endlesscheng-canj
class UnionFind {
public:
	UnionFind(int n) :fa(n) {
		// 一开始有n个集合 {0},{1}...{n-1}
		//集合i的代表元是自己
		ranges::iota(fa, 0);
	}

	//返回x所在集合的代表元
	//同时做路径压缩,也就是把x所在集合中所有元素的fa都改成代表元
	int find(int x) {
		//如果fa[x]==x,则表示x是代表元
		if (fa[x] != x) {
			fa[x] = find(fa[x]);//fa改成代表元
		}
		return fa[x];
	}

	//判断x和y是否在同一个集合
	bool is_same(int x, int y) {
		//如果x的代表元和y的代表元相同,那么x和y就在同一个集合
		//这就是代表元的作用:用来迅速判断两个元素是否在同一个集合
		return find(x) == find(y);
	}

	//把from所在集合合并到to所在集合中
	void merge(int from, int to) {
		int x = find(from), y = find(to);
		fa[x] = y;// 合并集合,修改后就可以认为from 和 to在同一个集合了
	}

private:
	vector<int> fa;	// 代表元
};

class Solution {
public:
	int latestDayToCross(int row, int col, vector<vector<int>>& cells) {
		int top = row * col;
		int bottom = row * col + 1;
		UnionFind uf(row * col + 2);
		vector<vector<int8_t>> land(row, vector<int8_t>(col));
		
		for (int day = cells.size() - 1;;day--) {
			auto& cell = cells[day];
			int r = cell[0] - 1; // 改成从0开始的下标
			int c = cell[1] - 1;
			int v = r * col + c;
			land[r][c] = true; //突变陆地

			if (r == 0) {
				uf.merge(v, top);// 与最上面相连
			}
			
			if (r == row - 1) {
				uf.merge(v, bottom);// 与最下面相连
			}

			for (auto& d : DIRS) {
				int x = r + d[0], y = c + d[1];
				if (0 <= x && x < row && 0 <= y && y < col && land[x][y]) {
					uf.merge(v, x * col + y);//与四周的陆地相连
				}
			}

			//最上边和最下边相连
			if (uf.is_same(top, bottom)) {
				return day;
			}
		}
	}

private:
	//左右上下
	static constexpr int DIRS[4][2] = { {0,-1},{0,1},{-1,0},{1,0} };
};
相关推荐
_OP_CHEN17 小时前
【从零开始的Qt开发指南】(十九)Qt 文件操作:从 I/O 设备到文件信息,一站式掌握跨平台文件处理
开发语言·c++·qt·前端开发·文件操作·gui开发·qt文件
CSDN_RTKLIB17 小时前
【std::map】双向迭代器说明
c++·stl
王老师青少年编程18 小时前
信奥赛C++提高组csp-s之欧拉回路
c++·算法·csp·欧拉回路·信奥赛·csp-s·提高组
No0d1es18 小时前
2025年12月 GESP CCF编程能力等级认证C++六级真题
c++·青少年编程·gesp·ccf·6级
Terrence Shen18 小时前
【CUDA编程系列】之01
c++·人工智能·深度学习·机器学习
墨有66618 小时前
数学分析栈的出栈顺序:从算法判断到数学本质(卡特兰数初探)
c++·算法·数学建模
liulilittle18 小时前
LIBTCPIP 技术探秘(tun2sys-socket)
开发语言·网络·c++·信息与通信·通信·tun
yyy(十一月限定版)18 小时前
c++(3)类和对象(中)
java·开发语言·c++
DYS_房东的猫19 小时前
写出第一个程序
c++