原题链接在这里: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. JQuery高级(一)

    JQuery 高级 1. 动画 2. 遍历 3. 事件绑定 4. 案例 5. 插件 1. 动画 1. 三种方式显示和隐藏元素 1. 默认显示和隐藏方式 1. show([speed,[easing], ...

  2. C++ 工程师养成 每日一题fourth (reverse的使用)

    题目: 将一句话的单词进行倒置,标点不倒置. 这道题最简单的解法是使用algorithm提供的reverse()函数 具体步骤我写在代码注释里面: #include <string> #i ...

  3. Python之路【第二十三篇】:数据库基础

    数据库的简介 数据库 数据库(database,DB)是指长期存储在计算机内的,有组织,可共享的数据的集合.数据库中的数据按一定的数学模型组织.描述和存储,具有较小的冗余,较高的数据独立性和易扩展性, ...

  4. 怎样遍历NodeList对象

    因为NodeList对象是一个类似数组的对象, 且它自带了一个 forEach() 方法, 因此可以使用 forEach() 遍历, 它的用法和 Array 里面的 forEach() 是完全一样的. ...

  5. mybatis逆向生成dao mapper和example.java文件

    mabatis插件 <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>myba ...

  6. AutoFac的简单使用教程

    Autofac可以对代码进行依赖注入,实现控制反转.以下是本菜鸟在初次入门时的代码配置,其源码,内部原理都还有待日后研究.目前也只是仅仅做到了能够使项目正常使用而已. 跟我一样刚刚入门的菜鸟朋友们可以 ...

  7. (转).Net Core控制台生成exe能独立运行

    原文介绍了两种方式,方式一经测试可用(生成exe在开发机器上可运行),但是因为服务器是windows server2012 r2,没有安装补丁,造成了困难,尚未在服务器上运行成功. (提示 api-m ...

  8. Java自学-数组 复制数组

    Java 如何复制数组 数组的长度是不可变的,一旦分配好空间,是多长,就多长,不能增加也不能减少 步骤 1 : 复制数组 把一个数组的值,复制到另一个数组中 System.arraycopy(src, ...

  9. Java 之 Session

    Session 一.概述 Session技术:服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象(HttpSession)中. 二.使用步骤 1.获取 HttpSession ...

  10. 【RAC】 RAC For W2K8R2 安装--卸载(八)

    [RAC] RAC For W2K8R2 安装--卸载(八) 一.1  BLOG文档结构图 一.2  前言部分 一.2.1  导读 各位技术爱好者,看完本文后,你可以掌握如下的技能,也可以学到一些其它 ...