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的更多相关文章

  1. HDU-4607 Park Visit bfs | DP | dfs

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4607 首先考虑找一条最长链长度k,如果m<=k+1,那么答案就是m.如果m>k+1,那么最 ...

  2. BFS和DFS详解

    BFS和DFS详解以及java实现 前言 图在算法世界中的重要地位是不言而喻的,曾经看到一篇Google的工程师写的一篇<Get that job at Google!>文章中说到面试官问 ...

  3. 算法录 之 BFS和DFS

    说一下BFS和DFS,这是个比较重要的概念,是很多很多算法的基础. 不过在说这个之前需要先说一下图和树,当然这里的图不是自拍的图片了,树也不是能结苹果的树了.这里要说的是图论和数学里面的概念. 以上概 ...

  4. 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 ...

  5. 算法学习之BFS、DFS入门

    算法学习之BFS.DFS入门 0x1 问题描述 迷宫的最短路径 给定一个大小为N*M的迷宫.迷宫由通道和墙壁组成,每一步可以向相邻的上下左右四格的通道移动.请求出从起点到终点所需的最小步数.如果不能到 ...

  6. 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/19617187 图的存储结构 本文的重点在于图的深度优先搜索(DFS)和广度优先搜索(BFS ...

  7. ACM__搜素之BFS与DFS

    BFS(Breadth_First_Search) DFS(Depth_First_Search) 拿图来说 BFS过程,以1为根节点,1与2,3相连,找到了2,3,继续搜2,2与4,相连,找到了4, ...

  8. BFS和DFS算法

    昨晚刚昨晚华为笔试题,用到了BFS和DFS,可惜自己学艺不精,忘记了实现原理,现在借用大佬写的内容给自己做个提高 转自:https://www.jianshu.com/p/70952b51f0c8 图 ...

  9. 通俗理解BFS和DFS,附基本模板

    1.BFS(宽度优先搜索):使用队列来保存未被检测的节点,按照宽度优先的顺序被访问和进出队列 打个比方:(1)类似于树的按层次遍历 (2)你的眼镜掉在了地上,你趴在地上,你总是先摸离你最近的地方,如果 ...

  10. [Algorithms] Graph Traversal (BFS and DFS)

    Graph is an important data structure and has many important applications. Moreover, grach traversal ...

随机推荐

  1. 利用GitLab自动同步软件仓库

    利用GitLab自动同步GitHub.Gitee.Bitbucket软件仓库 我在码云的账号:userName密码:password项目地址:https://gitee.com/Bytom/bytom ...

  2. ABP开发框架前后端开发系列---(8)ABP框架之Winform界面的开发过程

    在前面随笔介绍的<ABP开发框架前后端开发系列---(7)系统审计日志和登录日志的管理>里面,介绍了如何改进和完善审计日志和登录日志的应用服务端和Winform客户端,由于篇幅限制,没有进 ...

  3. window系统谷歌浏览器百度搜索框光标不能输入并且不显示光标----自制bug以及解决

    --------------------bug无处不在------------------------- 今天在搞代码的时候,保存文件无意中犯了个致命错误,文件名称写入非法字符,可能与Windows系 ...

  4. Netty源码分析--Channel注册(上)(五)

    其实在将这一节之前,我们来分析一个东西,方便下面的工作好开展. 打开启动类,最开始的时候创建了一个NioEventLoopGroup 事件循环组,我们来跟一下这个. 这里bossGroup, 我传入了 ...

  5. Elasticsearch的使用

    我这边是以elasticsearch-2.4.3为例:引入maven <dependency> <groupId>org.elasticsearch.client</gr ...

  6. 微信小程序商城(Java版)

    体验 后台演示地址(账号:admin 密码:admin) 小程序体验如下: 技术选型 1 后端使用技术 1.1 springframework4.3.7.RELEASE 1.2 mybatis3.1. ...

  7. 【工具】java 文本文档txt写出记录工具

    彩蛋!http://abowman.com/google-modules/dog/ 以下是自己小游戏生成人物经历的传记时保存txt所用到的工具类,功能简单,不多说什么,贴上代码: package co ...

  8. php防注入xss攻击

    <?php //php防注入和XSS攻击通用过滤. //by qq:831937 $_GET && SafeFilter($_GET); $_POST && Sa ...

  9. 使用 cxf的程序 在win10 测试部署时报空指针异常

    2018-11-08 15:50:55.072 DEBUG 21524 --- [nio-8080-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter  : ...

  10. ZOJ 3795:Grouping(缩点+最长路)

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5303 题意:有n个人m条边,每条边有一个u,v,代表u的年龄大于等于v,现在要 ...