1129. 颜色交替的最短路径
路径 颜色 交替 1129
2023-06-13 09:17:10 时间
解题思路:广度优先搜索
将红色和蓝色的边分别建图 搜索时使用数组记录 [当前节点,需要使用的颜色] 交替搜索即可 用0
表示红色,1
表示蓝色,对于颜色i
, 下一次的颜色即为i ^ 1
复杂度分析: 时间复杂度:O(n+r+b),其中
n
是节点数,r
是红边数,b
是蓝边数。 空间复杂度:O(n+r+b)
代码
class Solution {
public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
List<Integer>[][] es = new List[2][n];
for(int i = 0; i < n; i++){
es[0][i] = new ArrayList();
es[1][i] = new ArrayList();
}
for(int[] r : redEdges) es[0][r[0]].add(r[1]);
for(int[] b : blueEdges) es[1][b[0]].add(b[1]);
int[] ans = new int[n];
Arrays.fill(ans, -1);
ans[0] = 0;
Queue<int[]> q = new LinkedList();
q.offer(new int[]{0, 0});
q.offer(new int[]{0, 1});
boolean[][] visited = new boolean[2][n];
int dis = 1;
while(!q.isEmpty()){
for(int i = q.size(); i > 0; i--){
int[] pos = q.poll();
for(int next : es[pos[1]][pos[0]]){
if(visited[pos[1] ^ 1][next]) continue;
visited[pos[1] ^ 1][next] = true;
if(ans[next] == -1) ans[next] = dis;
q.offer(new int[]{next, pos[1] ^ 1});
}
}
dis++;
}
return ans;
}
}
相关文章
- LeetCode 112. 路径总和
- leetcode刷题(125)——931. 下降路径最小和
- LeetCode - #63 不同路径 II
- 使用标签配置项目路径详解编程语言
- Linux下文件路径指南(linux文件路劲)
- Linux虚拟路径:让企业实现更高效率(linux虚拟路径)
- Linux如何加载动态库路径?(linux加载动态库路径)
- Linux字体路径探索之旅(linux字体路径)
- Linux系统轻松实现路径导航(linux导航)
- Linux的分支:探索开源世界的新路径(linux的分支)
- MySQL解析SQL: 打开路径视窗之门(mysql解析sql)
- Linux之分支:探索发展路径(linux的分支)
- PHP在Linux环境中的路径解析(phplinux路径)
- 探究Redis持久化路径技术实现(查看redis持久化路径)
- 使用cxoracle操作Python的完美路径(cx_oracle 路径)
- Oracle 10基础配置路径修正与优化(oracle10基本配置)