BFS vs DFS
1 Clone Graph 1 copy ervery nodes by bfs 2 add neighbors
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node)
{
if (node == null) {
return node;
} List<UndirectedGraphNode> nodes = new ArrayList<>();
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
nodes.add(node);
map.put(node, new UndirectedGraphNode(node.label)); int start = ;
while (start < nodes.size()) {
UndirectedGraphNode head = nodes.get(start++);
for (int i = ; i < head.neighbors.size(); i++) {
UndirectedGraphNode neighbor = head.neighbors.get(i);
if (!map.containsKey(neighbor)) {
nodes.add(neighbor);
map.put(neighbor, new UndirectedGraphNode(neighbor.label));
}
}
} for (int i = ; i < nodes.size(); i++) {
UndirectedGraphNode newNode = map.get(nodes.get(i));
for (int j = ; j < nodes.get(i).neighbors.size(); j++) {
newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j)));
}
} return map.get(node);
}
2 Topological Sorting 1 store nodes and rudu 2 find nodes has 0 rudu 3 bfs
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
// write your code here
ArrayList<DirectedGraphNode> result = new ArrayList<>();
Map<DirectedGraphNode, Integer> map = new HashMap<>(); for (DirectedGraphNode node : graph) {
for (DirectedGraphNode neighbor : node.neighbors) {
if (map.containsKey(neighbor)) {
map.put(neighbor, map.get(neighbor) + );
} else {
map.put(neighbor, );
}
}
} for (DirectedGraphNode node : graph) {
if (!map.containsKey(node)) {
result.add(node);
}
} int start = ;
while (start < result.size()) {
DirectedGraphNode node = result.get(start++);
for (DirectedGraphNode neighbor : node.neighbors) {
map.put(neighbor, map.get(neighbor) - );
if (map.get(neighbor) == ) {
result.add(neighbor);
}
}
} return result;
}
3 Route Between Two Nodes in Graph bfs 1 hold visited and queue 2 bfs
public boolean hasRoute(ArrayList<DirectedGraphNode> graph,
DirectedGraphNode s, DirectedGraphNode t) {
if (s == t) {
return true;
} Queue<DirectedGraphNode> queue = new LinkedList<>();
Set<DirectedGraphNode> visited = new HashSet<>();
queue.add(s);
visited.add(s); while (!queue.isEmpty()){
DirectedGraphNode node = queue.poll();
for (DirectedGraphNode neighbor : node.neighbors) {
if (visited.contains(neighbor)) {
continue;
}
queue.add(neighbor);
visited.add(neighbor);
if (neighbor == t) {
return true;
}
}
} return false;
}
4 N-Queens
public ArrayList<ArrayList<String>> solveNQueens(int n)
{
// write your code here
ArrayList<ArrayList<String>> res = new ArrayList<>();
search(res, new ArrayList<Integer>(), n);
return res;
}
void search(ArrayList<ArrayList<String>> res, ArrayList<Integer> cols, int n) {
if (cols.size() == n) {
res.add(drawChessboard(cols));
return;
} for (int i = ; i < n; i++) {
if (!isValid(cols, i)) {
continue;
}
cols.add(i);
search(res, cols, n);
cols.remove(cols.size() - );
}
} ArrayList<String> drawChessboard(List<Integer> cols) {
ArrayList<String> result = new ArrayList<>();
for (int i = ; i < cols.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = ; j < cols.size(); j++) {
sb.append(cols.get(i) == j ? "Q" : ".");
}
result.add(sb.toString());
}
return result;
} boolean isValid(List<Integer> cols, int colIndex) {
int row = cols.size();
for (int i = ; i < cols.size(); i++) {
if (cols.get(i) == colIndex) {
return false;
} if (i + cols.get(i) == row + colIndex) {
return false;
} if (i - cols.get(i) == row - colIndex) {
return false;
}
}
return true;
}
5 Word Ladder
public int ladderLength(String start, String end, Set<String> dict)
{
if (dict == null) {
return ;
} if (start.equals(end)) {
return ;
} dict.add(end);
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(start);
int length = ; while (!queue.isEmpty()) {
length++;
int size = queue.size();
for (int i = ; i < size; i++) {
String word = queue.poll();
for (String newWord: getNextWords(word, dict)) {
if (visited.contains(newWord)) {
continue;
} if (newWord.equals(end)) {
return length;
} visited.add(newWord);
queue.add(newWord);
}
}
}
return ;
} List<String> getNextWords(String word, Set<String> dict) {
List<String> result = new ArrayList<>();
for (char c = 'a'; c <= 'z'; c++) {
for (int i = ; i < word.length(); i++) {
if (c == word.charAt(i)) {
continue;
}
String newWord = replace(word, i, c);
if (dict.contains(newWord)) {
result.add(newWord);
}
}
}
return result;
} String replace(String word, int i, char c) {
char[] arr = word.toCharArray();
arr[i] = c;
return new String(arr);
}
6 Word Ladder
public class Solution {
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return a list of lists of string
*/
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> result = new ArrayList<>();
Map<String, Integer> distance = new HashMap<>();
Map<String, List<String>> map = new HashMap<>(); dict.add(start);
dict.add(end); bfs(start, end, dict, distance, map); List<String> path = new ArrayList<>(); dfs(start, end, result, distance, map, path); return result;
} void dfs(String start, String cur, List<List<String>> result, Map<String, Integer> distance,
Map<String, List<String>> map, List<String> path) {
path.add(cur);
if (cur.equals(start)) {
Collections.reverse(path);
result.add(new ArrayList<>(path));
Collections.reverse(path);
} else {
for (String word : map.get(cur)) {
if (distance.containsKey(word) && distance.get(word) + == distance.get(cur)) {
dfs(start, word, result, distance, map, path);
}
}
}
path.remove(path.size() - );
} void bfs(String start, String end, Set<String> dict, Map<String, Integer> distance,
Map<String, List<String>> map) { Queue<String> queue = new LinkedList<>();
queue.offer(start);
distance.put(start, ); for(String word : dict) {
map.put(word, new ArrayList<String>());
} while (!queue.isEmpty()) {
String word = queue.poll();
for (String newWord: getNextWords(word, dict)) {
map.get(newWord).add(word);
if (!distance.containsKey(newWord)) {
distance.put(newWord, distance.get(word) + );
queue.offer(newWord);
}
}
}
} List<String> getNextWords(String word, Set<String> dict) {
List<String> result = new ArrayList<>();
for (char c = 'a'; c <= 'z'; c++) {
for (int i = ; i < word.length(); i++) {
if (c == word.charAt(i)) {
continue;
}
String newWord = replace(word, i, c);
if (dict.contains(newWord)) {
result.add(newWord);
}
}
}
return result;
} String replace(String word, int i, char c) {
char[] arr = word.toCharArray();
arr[i] = c;
return new String(arr);
}
}
7 Palindrome Partitioning
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res = new ArrayList<>();
ArrayList<String> path = new ArrayList<>();
dfs(s, , path, res);
return res;
}
void dfs(String s, int start, ArrayList<String> path, ArrayList<ArrayList<String>> res) {
if (start == s.length()) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < s.length(); i++) {
if (isValid(s, start, i)){
path.add(s.substring(start, i + ));
dfs(s, i + , path, res);
path.remove(path.size() - );
}
}
}
boolean isValid(String s, int left, int right) {
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {
return false;
}
}
return true;
}
BFS vs DFS的更多相关文章
- HDU-4607 Park Visit bfs | DP | dfs
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4607 首先考虑找一条最长链长度k,如果m<=k+1,那么答案就是m.如果m>k+1,那么最 ...
- BFS和DFS详解
BFS和DFS详解以及java实现 前言 图在算法世界中的重要地位是不言而喻的,曾经看到一篇Google的工程师写的一篇<Get that job at Google!>文章中说到面试官问 ...
- 算法录 之 BFS和DFS
说一下BFS和DFS,这是个比较重要的概念,是很多很多算法的基础. 不过在说这个之前需要先说一下图和树,当然这里的图不是自拍的图片了,树也不是能结苹果的树了.这里要说的是图论和数学里面的概念. 以上概 ...
- hdu--1026--Ignatius and the Princess I(bfs搜索+dfs(打印路径))
Ignatius and the Princess I Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (J ...
- 算法学习之BFS、DFS入门
算法学习之BFS.DFS入门 0x1 问题描述 迷宫的最短路径 给定一个大小为N*M的迷宫.迷宫由通道和墙壁组成,每一步可以向相邻的上下左右四格的通道移动.请求出从起点到终点所需的最小步数.如果不能到 ...
- 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)
转载请注明出处:http://blog.csdn.net/ns_code/article/details/19617187 图的存储结构 本文的重点在于图的深度优先搜索(DFS)和广度优先搜索(BFS ...
- ACM__搜素之BFS与DFS
BFS(Breadth_First_Search) DFS(Depth_First_Search) 拿图来说 BFS过程,以1为根节点,1与2,3相连,找到了2,3,继续搜2,2与4,相连,找到了4, ...
- BFS和DFS算法
昨晚刚昨晚华为笔试题,用到了BFS和DFS,可惜自己学艺不精,忘记了实现原理,现在借用大佬写的内容给自己做个提高 转自:https://www.jianshu.com/p/70952b51f0c8 图 ...
- 通俗理解BFS和DFS,附基本模板
1.BFS(宽度优先搜索):使用队列来保存未被检测的节点,按照宽度优先的顺序被访问和进出队列 打个比方:(1)类似于树的按层次遍历 (2)你的眼镜掉在了地上,你趴在地上,你总是先摸离你最近的地方,如果 ...
- [Algorithms] Graph Traversal (BFS and DFS)
Graph is an important data structure and has many important applications. Moreover, grach traversal ...
随机推荐
- 【入门】WebRTC知识点概览 | 内有技术干货免费下载
什么是WebRTC WebRTC 即Web Real-Time Communication(网页实时通信)的缩写,是一个支持网页浏览器之间进行实时数据传输(包括音频.视频.数据流)的技术.经过多年的发 ...
- Scala 学习之路(十)—— 函数 & 闭包 & 柯里化
一.函数 1.1 函数与方法 Scala中函数与方法的区别非常小,如果函数作为某个对象的成员,这样的函数被称为方法,否则就是一个正常的函数. // 定义方法 def multi1(x:Int) = { ...
- Spark学习之路(一)—— Spark简介
一.简介 Spark于2009年诞生于加州大学伯克利分校AMPLab,2013年被捐赠给Apache软件基金会,2014年2月成为Apache的顶级项目.相对于MapReduce的批处理计算,Spar ...
- 搭建本地pip源
搭建本地的pip源 开发环境部署机器的时候, 每次从网上下载pip包会很慢, 将需要的包和相关依赖下载到本地, 搭建一个本地源服务器. 基本都是安装多个包, 推荐使用文件的方式, 文件内容格式, 可以 ...
- SwiftLint:代码规范检查工具介绍
Swift-CodeStyle Checker:SwiftLint 介绍: SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 GitHub's Swift 代码风 ...
- Google play中下载apk
在 Google play中下载apk:先在Google play中找到该apk,再去找APK downloader(https://www.allfreeapk.com/),Google play的 ...
- 从零开始实现ASP.NET Core MVC的插件式开发(二) - 如何创建项目模板
标题:从零开始实现ASP.NET Core MVC的插件式开发(二) - 如何创建项目模板 作者:Lamond Lu 地址:https://www.cnblogs.com/lwqlun/p/11155 ...
- sql 中 并集union和union all的使用区别
union 操作符用于合并两个或多个 SELECT 语句的结果集,并且去除重复数据,按照数据库字段的顺序进行排序. 例 SELECT NAME FROM TABLE1UNIONSELECT EMP_ ...
- 实现markdown功能
前言 由于个人一直想弄一个博客网站,所以写博客的功能也就必须存在啦,而之前想过用富文本编辑器来实现的.但是接触了markdown后,发现真的是太好玩了,而且使用markdown的话可以在博客园.CSD ...
- 【深入浅出-JVM】(4):编译 jdk
环境 mac,xcode,jdk8,openjdk,autoconf 步骤 安装autoconf brew install autoconf 下载openjdk源码 git clone https:/ ...