Skip to content

Commit 2ffc5aa

Browse files
committed
feat: 深度优先遍历
1 parent 5046946 commit 2ffc5aa

5 files changed

+129
-3
lines changed

jest_html_reporters.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" contect="jest, reporters"><meta name="author" contect="hazyzh"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1,maximum-scale=1"><link rel="shortcut icon" href="data:image/png;base64,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"></head><title>Report</title><body><div id="app"></div><textarea style="display: none;" id="resData">
2-
"{\"numFailedTestSuites\":0,\"numFailedTests\":0,\"numPassedTestSuites\":4,\"numPassedTests\":6,\"numPendingTestSuites\":0,\"numPendingTests\":0,\"numRuntimeErrorTestSuites\":0,\"numTodoTests\":0,\"numTotalTestSuites\":4,\"numTotalTests\":6,\"openHandles\":[],\"snapshot\":{\"added\":0,\"didUpdate\":false,\"failure\":false,\"filesAdded\":0,\"filesRemoved\":0,\"filesRemovedList\":[],\"filesUnmatched\":0,\"filesUpdated\":0,\"matched\":0,\"total\":0,\"unchecked\":0,\"uncheckedKeysByFile\":[],\"unmatched\":0,\"updated\":0},\"startTime\":1631195912490,\"success\":false,\"testResults\":[{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":1,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631195920503,\"runtime\":6495,\"slow\":true,\"start\":1631195914008},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\graph.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"图\"],\"duration\":7,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"图 图测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"图测试\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":2,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631195920672,\"runtime\":6768,\"slow\":true,\"start\":1631195913904},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\red-black-tree.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"红黑树单元测试\"],\"duration\":8,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"红黑树单元测试 1.测试节点颜色非红即黑\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"1.测试节点颜色非红即黑\"},{\"ancestorTitles\":[\"红黑树单元测试\"],\"duration\":1,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"红黑树单元测试 2.测试根节点颜色是黑色\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"2.测试根节点颜色是黑色\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":1,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631195920773,\"runtime\":6933,\"slow\":true,\"start\":1631195913840},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\breadth-first-search.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"广度优先遍历测试\"],\"duration\":41,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"广度优先遍历测试 广度优先遍历\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"广度优先遍历\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":2,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631195921102,\"runtime\":506,\"slow\":false,\"start\":1631195920596},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\heap-sort.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"堆排序测试\"],\"duration\":8,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"堆排序测试 堆排序正序测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"堆排序正序测试\"},{\"ancestorTitles\":[\"堆排序测试\"],\"duration\":1,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"堆排序测试 堆排序逆序测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"堆排序逆序测试\"}],\"failureMessage\":null}],\"wasInterrupted\":false,\"config\":{\"bail\":0,\"changedFilesWithAncestor\":false,\"collectCoverage\":false,\"collectCoverageFrom\":[],\"coverageDirectory\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\coverage\",\"coverageProvider\":\"babel\",\"coverageReporters\":[\"json\",\"text\",\"lcov\",\"clover\"],\"detectLeaks\":false,\"detectOpenHandles\":false,\"errorOnDeprecated\":false,\"expand\":false,\"findRelatedTests\":false,\"forceExit\":false,\"json\":false,\"lastCommit\":false,\"listTests\":false,\"logHeapUsage\":false,\"maxConcurrency\":5,\"maxWorkers\":3,\"noStackTrace\":false,\"nonFlagArgs\":[],\"notify\":false,\"notifyMode\":\"failure-change\",\"onlyChanged\":false,\"onlyFailures\":false,\"passWithNoTests\":false,\"projects\":[],\"reporters\":[[\"default\",{}],[\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\node_modules\\\\jest-html-reporters\\\\index.js\",{}]],\"rootDir\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\",\"runTestsByPath\":false,\"skipFilter\":false,\"testFailureExitCode\":1,\"testPathPattern\":\"\",\"testSequencer\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\node_modules\\\\@jest\\\\test-sequencer\\\\build\\\\index.js\",\"updateSnapshot\":\"new\",\"useStderr\":false,\"watch\":false,\"watchAll\":false,\"watchman\":true},\"endTime\":1631195921331,\"_reporterOptions\":{\"publicPath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\",\"filename\":\"jest_html_reporters.html\",\"expand\":false,\"pageTitle\":\"\",\"hideIcon\":false,\"testCommand\":\"npx jest\",\"openReport\":false,\"multipleReportsUnitePath\":\"\",\"failureMessageOnly\":false,\"enableMergeData\":false,\"dataMergeLevel\":1},\"attachInfos\":{}}"
2+
"{\"numFailedTestSuites\":0,\"numFailedTests\":0,\"numPassedTestSuites\":4,\"numPassedTests\":6,\"numPendingTestSuites\":0,\"numPendingTests\":0,\"numRuntimeErrorTestSuites\":0,\"numTodoTests\":0,\"numTotalTestSuites\":4,\"numTotalTests\":6,\"openHandles\":[],\"snapshot\":{\"added\":0,\"didUpdate\":false,\"failure\":false,\"filesAdded\":0,\"filesRemoved\":0,\"filesRemovedList\":[],\"filesUnmatched\":0,\"filesUpdated\":0,\"matched\":0,\"total\":0,\"unchecked\":0,\"uncheckedKeysByFile\":[],\"unmatched\":0,\"updated\":0},\"startTime\":1631450068587,\"success\":false,\"testResults\":[{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":2,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631450076095,\"runtime\":6060,\"slow\":true,\"start\":1631450070035},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\heap-sort.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"堆排序测试\"],\"duration\":4,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"堆排序测试 堆排序正序测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"堆排序正序测试\"},{\"ancestorTitles\":[\"堆排序测试\"],\"duration\":1,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"堆排序测试 堆排序逆序测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"堆排序逆序测试\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":1,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631450076191,\"runtime\":6199,\"slow\":true,\"start\":1631450069992},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\graph.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"图\"],\"duration\":8,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"图 图测试\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"图测试\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":1,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631450076518,\"runtime\":6537,\"slow\":true,\"start\":1631450069981},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\breadth-first-search.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"广度优先遍历测试\"],\"duration\":7,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"广度优先遍历测试 广度优先遍历\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"广度优先遍历\"}],\"failureMessage\":null},{\"leaks\":false,\"numFailingTests\":0,\"numPassingTests\":2,\"numPendingTests\":0,\"numTodoTests\":0,\"openHandles\":[],\"perfStats\":{\"end\":1631450077458,\"runtime\":1275,\"slow\":false,\"start\":1631450076183},\"skipped\":false,\"snapshot\":{\"added\":0,\"fileDeleted\":false,\"matched\":0,\"unchecked\":0,\"uncheckedKeys\":[],\"unmatched\":0,\"updated\":0},\"testFilePath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\test\\\\red-black-tree.spec.js\",\"testResults\":[{\"ancestorTitles\":[\"红黑树单元测试\"],\"duration\":3,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"红黑树单元测试 1.测试节点颜色非红即黑\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"1.测试节点颜色非红即黑\"},{\"ancestorTitles\":[\"红黑树单元测试\"],\"duration\":0,\"failureDetails\":[],\"failureMessages\":[],\"fullName\":\"红黑树单元测试 2.测试根节点颜色是黑色\",\"invocations\":1,\"location\":null,\"numPassingAsserts\":0,\"status\":\"passed\",\"title\":\"2.测试根节点颜色是黑色\"}],\"failureMessage\":null}],\"wasInterrupted\":false,\"config\":{\"bail\":0,\"changedFilesWithAncestor\":false,\"collectCoverage\":false,\"collectCoverageFrom\":[],\"coverageDirectory\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\coverage\",\"coverageProvider\":\"babel\",\"coverageReporters\":[\"json\",\"text\",\"lcov\",\"clover\"],\"detectLeaks\":false,\"detectOpenHandles\":false,\"errorOnDeprecated\":false,\"expand\":false,\"findRelatedTests\":false,\"forceExit\":false,\"json\":false,\"lastCommit\":false,\"listTests\":false,\"logHeapUsage\":false,\"maxConcurrency\":5,\"maxWorkers\":3,\"noStackTrace\":false,\"nonFlagArgs\":[],\"notify\":false,\"notifyMode\":\"failure-change\",\"onlyChanged\":false,\"onlyFailures\":false,\"passWithNoTests\":false,\"projects\":[],\"reporters\":[[\"default\",{}],[\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\node_modules\\\\jest-html-reporters\\\\index.js\",{}]],\"rootDir\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\",\"runTestsByPath\":false,\"skipFilter\":false,\"testFailureExitCode\":1,\"testPathPattern\":\"\",\"testSequencer\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\\\\node_modules\\\\@jest\\\\test-sequencer\\\\build\\\\index.js\",\"updateSnapshot\":\"new\",\"useStderr\":false,\"watch\":false,\"watchAll\":false,\"watchman\":true},\"endTime\":1631450077531,\"_reporterOptions\":{\"publicPath\":\"C:\\\\workpalce\\\\data-structures-and-algorithms-by-javascript\",\"filename\":\"jest_html_reporters.html\",\"expand\":false,\"pageTitle\":\"\",\"hideIcon\":false,\"testCommand\":\"npx jest\",\"openReport\":false,\"multipleReportsUnitePath\":\"\",\"failureMessageOnly\":false,\"enableMergeData\":false,\"dataMergeLevel\":1},\"attachInfos\":{}}"
33
</textarea><script>/*! Copyright Harry All rights reserved. */!function(n){var r={};function o(t){if(r[t])return r[t].exports;var e=r[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,o),e.l=!0,e.exports}o.m=n,o.c=r,o.d=function(t,e,n){o.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},o.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,"a",e),e},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o.p="",o(o.s=1103)}([function(t,e,n){"use strict";t.exports=n(447)},function(t,e,n){t.exports=n(905)()},function(t,e,n){var r;
44
/*!
55
Copyright (c) 2017 Jed Watson.

src/code/24.breadth-first-search.js

+41
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,44 @@ export const breadthFirstSearch = (graph, startVertex, callback) => {
4848
}
4949
}
5050
};
51+
52+
export const BFS = (graph, startVertex) => {
53+
const vertices = graph.getVertices();
54+
const adjList = graph.getAdjList();
55+
const color = initializeColor(vertices);
56+
const queue = new Queue();
57+
const distances = {};
58+
const predecessors = {};
59+
60+
queue.enqueue(startVertex);
61+
62+
for (let i = 0; i < vertices.length; i++) {
63+
distances[vertices[i]] = 0;
64+
predecessors[vertices[i]] = null;
65+
}
66+
67+
while (!queue.isEmpty()) {
68+
const u = queue.dequeue();
69+
const neighbors = adjList.get(u);
70+
71+
color[u] = Colors.GREY;
72+
73+
for (let i = 0; i < neighbors.length; i++) {
74+
const w = neighbors[i];
75+
76+
if (color[w] === Colors.WHITE) {
77+
color[w] = Colors.GREY;
78+
distances[w] = distances[u] + 1;
79+
predecessors[w] = u;
80+
queue.enqueue(w);
81+
}
82+
}
83+
84+
color[u] = Colors.BLACK;
85+
}
86+
87+
return {
88+
distances,
89+
predecessors, // 前溯点数组
90+
};
91+
};

src/code/25.depth-first-search.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export const depthFirstSearch = (graph, callback) => {
2+
const vertices = graph.getVertices();
3+
const adjList = graph.getAdjList();
4+
const color = initializeColor(vertices);
5+
for (let i = 0; i < vertices.length; i++) {
6+
if (color[vertices[i]] === Colors.WHITE) {
7+
depthFirstSearchVisit(vertices[i], color, adjList, callback);
8+
}
9+
}
10+
};
11+
12+
const depthFirstSearchVisit = (u, color, adjList, callback) => {
13+
color[u] = Colors.GREY;
14+
if (callback) {
15+
callback(u);
16+
}
17+
18+
const neighbors = adjList.get(u);
19+
20+
for (let i = 0; i < neighbors.length; i++) {
21+
const w = neighbors[i];
22+
if (color[w] === Colors.WHITE) {
23+
depthFirstSearchVisit(w, color, adjList, callback);
24+
}
25+
}
26+
27+
color[u] = Colors.BLACK;
28+
};

src/index.js

+26-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { RedBlackTree } from "./code/21.RedBlackTree.js";
1818
import { MaxHeap, MinHeap } from "./code/22.MinHeap.js";
1919
import heapSort from "./sort/heap-sort.js";
2020
import { Graph } from "./code/23.Graph.js";
21-
import { breadthFirstSearch } from "./code/24.breadth-first-search.js";
21+
import { breadthFirstSearch, BFS } from "./code/24.breadth-first-search.js";
2222

2323
const graph = new Graph();
2424
const myVertices = ["A", "B", "C", "D", "E", "F", "G", "H", "I"];
@@ -43,6 +43,31 @@ const printVertex = (value) => {
4343

4444
breadthFirstSearch(graph, myVertices[0], printVertex);
4545

46+
const shortestPathA = BFS(graph, myVertices[0]);
47+
48+
console.log(shortestPathA);
49+
50+
const fromVertex = myVertices[0];
51+
52+
for (let i = 1; i < myVertices.length; i++) {
53+
const toVertex = myVertices[i];
54+
const path = new Stack();
55+
56+
for (let v = toVertex; v !== fromVertex; v = shortestPathA.predecessors[v]) {
57+
path.push(v);
58+
}
59+
60+
path.push(fromVertex);
61+
62+
let s = path.pop();
63+
64+
while (!path.isEmpty()) {
65+
s += " - " + path.pop();
66+
}
67+
68+
console.log(s);
69+
}
70+
4671
export {
4772
LinkList,
4873
Node,

0 commit comments

Comments
 (0)