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 ...
随机推荐
- vue数据加载等待组件
关于loading组件的. loading.vue <template> <div class="loading"> <div class=" ...
- Flume —— 安装部署
一.前置条件 Flume需要依赖JDK 1.8+,JDK安装方式见本仓库: Linux环境下JDK安装 二 .安装步骤 2.1 下载并解压 下载所需版本的Flume,这里我下载的是CDH版本的Flum ...
- 浅入深出Vue:事件处理
上一篇的最后留下了一个 v-on的思考,也就是本章的主题:事件处理 为什么需要事件处理 在前端开发中,经常要面对各种表单.按钮.而这里面就住着一个事件:点击 (click). 前端童鞋们肯定不陌生它, ...
- Spring Boot2(六):使用Spring Boot整合AOP面向切面编程
一.前言 众所周知,spring最核心的两个功能是aop和ioc,即面向切面和控制反转.本文会讲一讲SpringBoot如何使用AOP实现面向切面的过程原理. 二.何为aop aop全称Aspec ...
- 如何配置selinux
参考命令: 一.开启/关闭selinux getenforce:查看selinux运行状态 setenforce 0 :关闭selinux setenforce 1 :开启selinux 系统 ...
- ES5_05_Function扩展
Function 构造器的语法: 注意: 参数 arg1 , arg2 , argN 被函数使用的参数的名称必须是合法命名的.参数名称是一个有效的JavaScript标识符的字符串,或者一个用逗号分隔 ...
- python初识(3)
bool 字符串 for循环 bool 数字非零全都是True 字符串非空全都是True 字符串 索引 从0开始 0 切片选取 [x:y] 左闭右开区间 [x:y:z] 选取x到y之间 每隔z选取一次 ...
- [golang]golang time.After内存泄露问题分析
无意中看到一篇文章说,当在for循环里使用select + time.After的组合时会产生内存泄露,于是进行了复现和验证,以此记录 内存泄露复现 问题复现测试代码如下所示: package mai ...
- 《Python 3.5从零开始学》笔记-第8章 面向对象编程
前几章包括开启python之旅.列表和元组.字符串.字典.条件和循环等语句.函数等基本操作.主要对后面几章比较深入的内容记录笔记. 第8章 面向对象编程 8.3深入类 #!/usr/local/bin ...
- 环形缓存RingBuf的几种实现方式(数组,链表),及Disruptor的分析
先贴个头文件的设计: 首先缓冲区中没有任何数据时,nIdWrite.nIdRead读写下标都为0. 为了判断缓冲区中是否还有数据可读或者可写,我判断的依据是:1)当nIdWrite 等于 nIdRea ...