原题链接在这里:https://leetcode.com/problems/shortest-path-with-alternating-colors/

题目:

Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.

Each [i, j] in red_edges denotes a red directed edge from node i to node j.  Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.

Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).

Example 1:

Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]

Example 2:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]

Example 3:

Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]

Example 4:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]

Example 5:

Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]

Constraints:

  • 1 <= n <= 100
  • red_edges.length <= 400
  • blue_edges.length <= 400
  • red_edges[i].length == blue_edges[i].length == 2
  • 0 <= red_edges[i][j], blue_edges[i][j] < n

题解:

To calculate the shortest path, use BFS.

Construct the graph, for each node, put its neighbors into 2 different sets based on edge colors.

res array also have 2 rows, shortest paths from different edges.

Add {0, 0}, {1, 0} into queue representing starting node with different colored edges.

When pulling out cur. cur[0] is the color going out, cur[1] is the node i. find it neighbor by graph[cur[0]][cur[1]].

For each neighbor, it needs to spread out with different color 1- cur[0]. Thus check res[1-cur[0]][nei].

If it has been visited before, it should still be Integer.MAX_VALUE, update it with current step res[cur[0]][cur[1]] + 1. And add it to queue.

Finally get the smallest steps for each of the nodes.

Note: Set<Integer> [][] graph = new Set[2][n]. Declared type must include type Integer. Constructor can't put <Integer> after Set.

Time Complexity: O(n+E). Perform 2 BFS iterations. E = red_edges.length + blue_edges.length.

Space: O(n).

AC Java:

 class Solution {
public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) {
Set<Integer> [][] graph = new Set[2][n];
for(int i = 0; i<n; i++){
graph[0][i] = new HashSet<>();
graph[1][i] = new HashSet<>();
} for(int [] red : red_edges){
graph[0][red[0]].add(red[1]);
} for(int [] blue : blue_edges){
graph[1][blue[0]].add(blue[1]);
} int [][] res = new int[2][n];
for(int i = 1; i<n; i++){
res[0][i] = Integer.MAX_VALUE;
res[1][i] = Integer.MAX_VALUE;
} LinkedList<int []> que = new LinkedList<int []>();
que.add(new int[] {0, 0});
que.add(new int[] {1, 0});
while(!que.isEmpty()){
int [] cur = que.poll();
int row = cur[0];
int i = cur[1];
for(int nei : graph[row][i]){
if(res[1-row][nei] == Integer.MAX_VALUE){
res[1-row][nei] = res[row][i]+1;
que.add(new int[]{1-row, nei});
}
}
} int [] resArr = new int[n];
for(int i = 0; i<n; i++){
int min = Math.min(res[0][i], res[1][i]);
resArr[i] = min == Integer.MAX_VALUE ? -1 : min;
} return resArr;
}
}

1129. Shortest Path with Alternating Colors的更多相关文章

  1. 【leetcode】1129. Shortest Path with Alternating Colors

    题目如下: Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is ei ...

  2. hdu-----(2807)The Shortest Path(矩阵+Floyd)

    The Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  3. zoj 2760 How Many Shortest Path 最大流

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...

  4. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  5. hdu 3631 Shortest Path(Floyd)

    题目链接:pid=3631" style="font-size:18px">http://acm.hdu.edu.cn/showproblem.php?pid=36 ...

  6. Shortest Path(思维,dfs)

    Shortest Path  Accepts: 40  Submissions: 610  Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: ...

  7. Shortest Path

    Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)T ...

  8. (中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

  9. 【ZOJ2760】How Many Shortest Path

    How Many Shortest Path 标签: 网络流 描述 Given a weighted directed graph, we define the shortest path as th ...

随机推荐

  1. Android调试桥 adb安装详解

    Android调试桥(adb) 一.简介 Android 调试桥 (adb) 是一种功能多样的命令行工具,可让您与设备进行通信.adb 命令便于执行各种设备操作(例如安装和调试应用),并提供对 Uni ...

  2. 手撕面试官系列(十一):BAT面试必备之常问85题

    JVM专题 (面试题+答案领取方式见侧边栏)  Java 类加载过程? 描述一下 JVM 加载 Class 文件的原理机制? Java 内存分配. GC 是什么? 为什么要有 GC? 简述 Java ...

  3. vps建站施工预告

    作为一个小白,最近几天自己用vps搭了个站点,用来发发博客,偶尔还可以去外面看看.后面几章就来记一下过程吧! 结构极为简单,建站用的WordPress,目前也就只有最基础的发文章功能.不过由于习惯了m ...

  4. javascript document.createElement() document.createTextNode() appendChild()

    //--------------document.createElement("div") var div = document.createElement("div&q ...

  5. 用python读取word文件里的表格信息【华为云技术分享】

    在企查查查询企业信息的时候,得到了一些word文件,里面有些控股企业的数据放在表格里,需要我们将其提取出来. word文件看起来很复杂,不方便进行结构化.实际上,一个word文档中大概有这么几种类型的 ...

  6. C# 单元测试学习笔记

    1.什么是单元测试         2.单元测试的好处 (1)协助程序员尽快找到代码中bug的具体位置 (2)能够让程序员对自己的程序更有自信 (3)能够让程序员在提交项目之前就将代码变的更加的强壮 ...

  7. 2019 世纪龙java面试笔试题 (含面试题解析)

      本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.世纪龙等公司offer,岗位是Java后端开发,因为发展原因最终选择去了世纪龙,入职一年时间了,也成为了面试官 ...

  8. 小米手机安装Google框架

    方法一 打开应用商店,搜索谷歌安装器下载即可. 方法二 搜索Gmail.Google+.Youtube等软件跳到豌豆荚,自动下载Google框架.

  9. 设计模式--Bulider模式

    起因:最近在做统计计算,创建的实体中属性比较多,都是一些数值,一开始是通过get.set方法进行赋值,占用了很多业务代码方法的长度,可读性不太好,后来改用了添加构造器的方式,稍显精简了一点,但是每次赋 ...

  10. Matlab观察者模式

    要点: 1.服务端(Subject)维护一个观察者的列表,以便能够向所有的观察者(Observer)推送信息 2.观察者可以获取服务端的状态 3.服务端和观察者可抽象,可以有多个不同实现 Subjec ...