图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦。

求最短路径:

127. Word Ladder

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.

All words contain only lowercase alphabetic characters.

从起点开始向外更新,因为每条路径的权值都不是负数,所以先更新的总比后更新的小。

已经被更新过的之后就不用考虑了

133. Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
/ \
/ \
0 --- 2
/ \
\_/
关键要用一个图把旧的节点和新的节点一一对应起来,并用一个队列存储需要更新neighbor的节点,每次加入到某一个链表中的新节点,只在map中放入neighbor没有更新的新节点,待从queue中读到的时候再处理。
261. Graph Valid Tree

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

For example:

Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

Hint:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

public class Solution {
public boolean validTree(int n, int[][] edges) {
List<HashSet<Integer>> sets = new ArrayList<HashSet<Integer>>();
for (int i = 0; i < n; i++) {
sets.add(new HashSet<Integer>());
}
boolean[] isVisited = new boolean[n];
Arrays.fill(isVisited, false);
for (int[] edge : edges) {
int v1 = edge[0];
int v2 = edge[1];
sets.get(v1).add(v2);
sets.get(v2).add(v1);
}
boolean result = dfs(sets, isVisited, 0, -1);
if (!result) {
return false;
}
for (int i = 0; i < n; i++) {
if (!isVisited[i]) {
return false;
}
}
return true;
}
private boolean dfs(List<HashSet<Integer>> sets, boolean[] isVisited, int now, int prev) {
boolean isV = isVisited[now];
if (isV) {
return false;
}
isVisited[now] = true;
for (Integer x : sets.get(now)) {
if (x != prev && !dfs(sets, isVisited, x, now)) {
return false;
}
}
return true;
}
}

310. Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

Example 1:

Given n = 4edges = [[1, 0], [1, 2], [1, 3]]

        0
|
1
/ \
2 3

return [1]

Example 2:

Given n = 6edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
\ | /
3
|
4
|
5

return [3, 4]

Hint:

  1. How many MHTs can a graph have at most?

Note:

(1) According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

public class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
List<List<Integer>> graph = new ArrayList<List<Integer>>(n);
if (n < 3 || edges.length == 0) {
List<Integer> result = new ArrayList<Integer>();
if (n == 0) {
return result;
} else {
for (int i = 0; i < n; i++) {
result.add(i);
}
return result;
}
}
for (int i = 0; i < n; i++) {
List<Integer> list = new LinkedList<Integer>();
graph.add(list);
}
for (int[] edge : edges) {
int v1 = edge[0];
int v2 = edge[1];
graph.get(v1).add(v2);
graph.get(v2).add(v1);
}
int count = n;
List<Integer> toRemove = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
List<Integer> list = graph.get(i);
if (list.size() == 1) {
toRemove.add(i);
}
}
while (!toRemove.isEmpty() && count > 1) {
List<Integer> tmpRemove = new ArrayList<Integer>();
for (Integer leave : toRemove) {
List<Integer> list0 = graph.get(leave);
int parent = list0.get(0);
list0.clear();
List<Integer> list = graph.get(parent);
list.remove(leave);
if (list.size() == 1) {
tmpRemove.add(parent);
}
}
count -= toRemove.size();
toRemove = tmpRemove;
if (count <= 2) {
break;
}
}
List<Integer> result = new ArrayList<Integer>();
result.addAll(toRemove);
return result;
}
}

[leetcode] 题型整理之图论的更多相关文章

  1. [leetcode] 题型整理之二叉树

    94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' va ...

  2. [leetcode] 题型整理之动态规划

    动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助 55. Jump Game Given an array of non-negative integers, you are ini ...

  3. [leetcode] 题型整理之排列组合

    一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...

  4. [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余

    需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...

  5. [leetcode] 题型整理之cycle

    找到环的起点. 一快一慢相遇初,从头再走再相逢.

  6. [leetcode]题型整理之用bit统计个数

    137. Single Number II Given an array of integers, every element appears three times except for one. ...

  7. [leetcode] 题型整理之查找

    1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...

  8. [leetcode] 题型整理之排序

    75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...

  9. [leetcode] 题型整理之字符串处理

    71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example,path = &q ...

随机推荐

  1. 耗时两月,NHibernate系列出炉

    写在前面 这篇总结本来是昨天要写的,可昨天大学班长来视察工作,多喝了点,回来就倒头就睡了,也就把这篇总结的文章拖到了今天. nhibernate系列从开始着手写,到现在前后耗费大概两个月的时间,通过总 ...

  2. Excel—使用条件格式标注今日值班者

    如下图所示值班表: Step1:选中A2:G2,调出条件格式,在条件格式中,使用公式确定单元格. Step2: 在公式栏中填入以下公式: =TEXT(TODAY(),"aaaa") ...

  3. SQL Server群集如何在线检测

    SQL Server群集知识介绍 Windows群集安装 基于iSCSI的SQL Server 2012群集测试 前言 群集的检测是调用dll资源,例如对于共享存储,ip,网络名称与DTC 这类Win ...

  4. js作用域

    一.js没有块级作用域 在c,java等语言中花括号里的代码都有自己的作用域,而js花括号没有块级作用域,经常会导致一些困惑,不明所以.例如: console.info(color); if(true ...

  5. Hibernate简易原生DAO的实现

    写在最前: 初学Hibernate,在尝试把JDBC项目移植到Hibernate的过程中,碰到了不少的麻烦,最让人心烦意乱的自然是SQL语句改动造成的代码混乱.其实不难,网上的解决方案有很多, 不过. ...

  6. [Computational Advertising] 计算广告学笔记之基础概念

    因为工作需要,最近一直在关注计算广告学的内容.作为一个新手,学习计算广告学还是建议先看一下刘鹏老师在师徒网的教程<计算广告学>. 有关刘鹏老师的个人介绍:刘鹏现任360商业产品首席架构师, ...

  7. php打印中文乱码

    php文档的文本格式都设置成 utf-8 格式 在代码中添加 header("content-type:text/html; charset=utf-8");

  8. 关于PHP的引用赋值

    应用赋值,可以改变之前的变量的值! 可以间接的做到,在变量未申明的时候!就可以获取它的值!

  9. Unix网络单词汇总

    Chrome开发者工具 Elements(元素).Network(网络).Sources(源代码:调试JS的地方).Timeline(时间线).Profiles(性能分析).Resources(资源: ...

  10. nginx使用ngx_lua访问后端Thrift-Server实现和介绍

    背景 随着openresty的出现,让nginx使用lua解决一些业务的能力大幅度提高,ngx_lua可以使用nginx自生的基于事件驱动的IO模型,和后端的存储,业务等系统实现非阻塞的连接交互. 如 ...