Kako implementirati 8 osnovnih algoritama grafikona u JavaScript

U ovom ću članku implementirati 8 algoritama grafova koji istražuju probleme pretraživanja i kombinatornosti (zaokretanje, najkraći put i podudaranje) grafova u JavaScriptu.

Problemi su posuđeni iz knjige "Elementi programskih intervjua na Javi". Rješenja u knjizi kodirana su na Javi, Pythonu ili C ++-u, ovisno o tome koju verziju knjige posjedujete.

Iako je logika koja stoji iza modeliranja problema jezično-agnostička, isječci koda koje navodim u ovom članku koriste neka JavaScript upozorenja.

Svako rješenje za svaki problem podijeljeno je u 3 odjeljka: pregled rješenja, pseudokod i na kraju stvarni kôd u JavaScript-u.

Da biste testirali kôd i vidjeli da radi ono što treba, možete upotrijebiti Chromeove razvojne alate za pokretanje isječaka na samom pregledniku ili pomoću NodeJS za njihovo pokretanje iz naredbenog retka.

Implementacija grafa

2 najčešće korištena prikaza grafikona su popis susjedstva i matrica susjedstva.

Problemi koje ću riješiti su za rijetke grafove (nekoliko bridova), a operacije vrhova u pristupu popisa susjedstva uzimaju konstantno (dodavanje vrha, O (1)) i linearno vrijeme (brisanje vrha, O (V + E ))). Stoga ću se većinom držati te provedbe.

Izbacimo to jednostavnom neusmjerenom, neponderiranom implementacijom grafa koristeći popis susjedstva . Održavat ćemo objekt (adjacencyList) koji će sadržavati sve vrhove na našem grafu kao ključeve. Vrijednosti će biti niz svih susjednih vrhova. U primjeru dolje, vrh 1 povezan je s vrhovima 2 i 4, dakle adjacencyList: {1: [2, 4]} i tako dalje za ostale vrhove.

Za izgradnju grafa imamo dvije funkcije: addVertex i addEdge . addVertex koristi se za dodavanje vrha na popis. addEdge se koristi za povezivanje vrhova dodavanjem susjednih vrhova u izvorni i odredišni niz, jer je ovo neusmjereni graf. Da bismo napravili usmjereni graf, jednostavno možemo ukloniti retke 14-16 i 18 u donjem kodu.

Prije uklanjanja vrha, moramo prelistati niz susjednih vrhova i ukloniti sve moguće veze s tim vrhom.

class Graph { constructor() { this.adjacencyList = {}; } addVertex(vertex) { if (!this.adjacencyList[vertex]) { this.adjacencyList[vertex] = []; } } addEdge(source, destination) { if (!this.adjacencyList[source]) { this.addVertex(source); } if (!this.adjacencyList[destination]) { this.addVertex(destination); } this.adjacencyList[source].push(destination); this.adjacencyList[destination].push(source); } removeEdge(source, destination) { this.adjacencyList[source] = this.adjacencyList[source].filter(vertex => vertex !== destination); this.adjacencyList[destination] = this.adjacencyList[destination].filter(vertex => vertex !== source); } removeVertex(vertex) { while (this.adjacencyList[vertex]) { const adjacentVertex = this.adjacencyList[vertex].pop(); this.removeEdge(vertex, adjacentVertex); } delete this.adjacencyList[vertex]; } }

Grafičke zaokreti

Nadovezujući se na našu implementaciju grafova u prethodnom odjeljku, implementirat ćemo zaokretanje grafova: prvo pretraživanje u širinu i prvo pretraživanje u dubinu.

Širina prvo pretraživanje

BFS posjećuje čvorove po jednu razinu . Da bismo spriječili posjećivanje istog čvora više puta, održavat ćemo posjećeni objekt.

Budući da čvorove trebamo obraditi na način First In First Out, red je dobar kandidat za upotrebu strukture podataka. Složenost vremena je O (V + E).

function BFS Initialize an empty queue, empty 'result' array & a 'visited' map Add the starting vertex to the queue & visited map While Queue is not empty: - Dequeue and store current vertex - Push current vertex to result array - Iterate through current vertex's adjacency list: - For each adjacent vertex, if vertex is unvisited: - Add vertex to visited map - Enqueue vertex Return result array

Dubina Prvo pretraživanje

DFS pametno posjećuje dubinu čvorova. Budući da čvorove trebamo obraditi na način Last In First Out, koristit ćemo stog .

Polazeći od vrha, gurnut ćemo susjedne vrhove u svoj stog. Kad god se vrh pojavi, on je označen kao posjećen u našem posjećenom objektu. Njeni susjedni vrhovi gurnuti su u hrpu. Budući da uvijek iskačemo novi susjedni vrh, naš algoritam uvijek će istraživati ​​novu razinu .

Također možemo koristiti unutarnje pozive steka za rekurzivnu implementaciju DFS-a. Logika je ista.

Složenost vremena je ista kao i BFS, O (V + E).

function DFS Initialize an empty stack, empty 'result' array & a 'visited' map Add the starting vertex to the stack & visited map While Stack is not empty: - Pop and store current vertex - Push current vertex to result array - Iterate through current vertex's adjacency list: - For each adjacent vertex, if vertex is unvisited: - Add vertex to visited map - Push vertex to stack Return result array
Graph.prototype.bfs = function(start) { const queue = [start]; const result = []; const visited = {}; visited[start] = true; let currentVertex; while (queue.length) { currentVertex = queue.shift(); result.push(currentVertex); this.adjacencyList[currentVertex].forEach(neighbor => { if (!visited[neighbor]) { visited[neighbor] = true; queue.push(neighbor); } }); } return result; } Graph.prototype.dfsRecursive = function(start) { const result = []; const visited = {}; const adjacencyList = this.adjacencyList; (function dfs(vertex){ if (!vertex) return null; visited[vertex] = true; result.push(vertex); adjacencyList[vertex].forEach(neighbor => { if (!visited[neighbor]) { return dfs(neighbor); } }) })(start); return result; } Graph.prototype.dfsIterative = function(start) { const result = []; const stack = [start]; const visited = {}; visited[start] = true; let currentVertex; while (stack.length) { currentVertex = stack.pop(); result.push(currentVertex); this.adjacencyList[currentVertex].forEach(neighbor => { if (!visited[neighbor]) { visited[neighbor] = true; stack.push(neighbor); } }); } return result; }

Pretražite Maze

Izjava o problemu:

S obzirom na 2D niz crno-bijelih unosa koji predstavljaju labirint s određenim ulaznim i izlaznim točkama, pronađite put od ulaza do izlaza, ako takav postoji. - Aziz, Adnan i sur. Elementi programskih intervjua

Predstavljat ćemo bijele unose s 0 i crne unose s 1. Bijeli ulazi predstavljaju otvorena područja, a crni zidovi. Ulazna i izlazna točka predstavljene su nizom, indeksom 0 i indeksom prvog ispunjenim indeksima redaka i stupaca.

Riješenje:

  • Da bismo se pomaknuli u drugi položaj, teško ćemo kodirati četiri moguća kretanja u nizu smjerova (desno, dolje, lijevo i gore; bez dijagonalnih pomicanja):
[ [0,1], [1,0], [0,-1], [-1,0] ]
  • Pratiti stanica koje smo već posjetili, mi ćemo zamijeniti bijeli unose ( 0-a ) s crnim unosa ( +1 ). U osnovi koristimo DFS rekurzivno za prelazak labirinta. Osnovni slučaj, koji će završiti rekurziju, jest ili smo dosegli izlaznu točku i vratili se true ili smo posjetili svaki bijeli ulaz i povratak false .
  • Još jedna važna stvar koju moramo pratiti je osigurati da smo cijelo vrijeme u granicama labirinta i da nastavimo samo ako smo na bijelom ulazu . Za to će se pobrinuti funkcija isFeasible .
  • Složenost vremena: O (V + E)

Pseudokod:

function hasPath Start at the entry point While exit point has not been reached 1. Move to the top cell 2. Check if position is feasible (white cell & within boundary) 3. Mark cell as visited (turn it into a black cell) 4. Repeat steps 1-3 for the other 3 directions
var hasPath = function(maze, start, destination) { maze[start[0]][start[1]] = 1; return searchMazeHelper(maze, start, destination); }; function searchMazeHelper(maze, current, end) { // dfs if (current[0] == end[0] && current[1] == end[1]) { return true; } let neighborIndices, neighbor; // Indices: 0->top,1->right, 2->bottom, 3->left let directions = [ [0,1] , [1,0] , [0,-1] , [-1,0] ]; for (const direction of directions) { neighborIndices = [current[0]+direction[0], current[1]+direction[1]]; if (isFeasible(maze, neighborIndices)) { maze[neighborIndices[0]][neighborIndices[1]] = 1; if (searchMazeHelper(maze, neighborIndices, end)) { return true; } } } return false; } function isFeasible(maze, indices) { let x = indices[0], y = indices[1]; return x >= 0 && x = 0 && y < maze[x].length && maze[x][y] === 0; } var maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]] hasPath(maze, [0,4], [3,2]);

Obojite logičku matricu

Izjava o problemu:

Provedite rutinu koja uzima n X m logički niz A zajedno s unosom (x, y) i preokreće boju regije povezane s (x, y). - Aziz, Adnan i sur. Elementi programskih intervjua

Dvije boje bit će predstavljene s 0 i 1.

U donjem primjeru započinjemo u središtu niza ([1,1]). Imajte na umu da iz tog položaja možemo doći samo do gornje, krajnje lijeve trokutaste matrice. Ne može se doseći krajnji desni, najniži položaj ([2,2]). Dakle, na kraju postupka to je jedina boja koja se ne preokreće.

Riješenje:

  • Kao i u prethodnom pitanju, kodirat ćemo niz da definiramo 4 moguća poteza.
  • Upotrijebit ćemo BFS za prelazak grafa.
  • Neznatno ćemo izmijeniti funkciju isFeasible. I dalje će provjeravati je li novi položaj u granicama matrice. Drugi je uvjet da je novi položaj obojen jednako kao i prethodni položaj. Ako novi položaj odgovara zahtjevima, njegova se boja preokreće.
  • Složenost vremena: O (mn)

Pseudokod:

function flipColor Start at the passed coordinates and store the color Initialize queue Add starting position to queue While Queue is not empty: - Dequeue and store current position - Move to the top cell 1. Check if cell is feasible 2. If feasible, - Flip color - Enqueue cell 3. Repeat steps 1-2 for the other 3 directions
function flipColor(image, x, y) { let directions = [ [0,1] , [1,0] , [0,-1] , [-1,0] ]; let color = image[x][y]; let queue = []; image[x][y] = Number(!color); queue.push([x,y]); let currentPosition, neighbor; while (queue.length) { currentPosition = queue.shift(); for (const direction of directions) { neighbor = [currentPosition[0]+direction[0], currentPosition[1]+direction[1]]; if (isFeasible(image, neighbor, color)) { image[neighbor[0]][neighbor[1]] = Number(!color); queue.push([neighbor[0], neighbor[1]]); } } } return image; } function isFeasible(image, indices, color) { let x = indices[0], y = indices[1]; return x >= 0 && x = 0 && y < image[x].length && image[x][y] == color; } var image = [[1,1,1],[1,1,0],[1,0,1]]; flipColor(image,1,1);

Izračunaj zatvorene regije

Izjava o problemu:

Neka je A 2D niz čiji su unosi W ili B. Napišite program koji uzima A i zamjenjuje sve W koji ne mogu doći do granice s B. - Aziz, Adnan, et al. Elementi programskih intervjua

Riješenje:

  • Instead of iterating through all the entries to find the enclosed W entries, it is more optimal to start with the boundary W entries, traverse the graph and mark the connected W entries. These marked entries are guaranteed to be not enclosed since they are connected to a W entry on the border of the board. This preprocessing is basically the complement of what the program has to achieve.
  • Then, A is iterated through again and the unmarked W entries (which will be the enclosed ones) are changed into the B entries.
  • We’ll keep track of the marked and unmarked W entries using a Boolean array of the same dimensions as A. A marked entry will be set to true.
  • Time complexity: O(mn)

Pseudocode:

function fillSurroundedRegions 1. Initialize a 'visited' array of same length as the input array pre-filled with 'false' values 2. Start at the boundary entries 3. If the boundary entry is a W entry and unmarked: Call markBoundaryRegion function 4. Iterate through A and change the unvisited W entry to B function markBoundaryRegion Start with a boundary W entry Traverse the grid using BFS Mark the feasible entries as true
function fillSurroundedRegions(board) { if (!board.length) { return; } const numRows = board.length, numCols = board[0].length; let visited = []; for (let i=0; i
    

Deadlock Detection (Cycle In Directed Graph)

Problem Statement:

One deadlock detection algorithm makes use of a “wait-for” graph to track which other processes a process is currently blocking on. In a wait-for graph, processes are represented as nodes, and an edge from process P to 0 implies 0 is holding a resource that P needs and thus P is waiting for 0 to release its lock on that resource. A cycle in this graph implies the possibility of a deadlock. This motivates the following problem.

Write a program that takes as input a directed graph and checks if the graph contains a cycle. – Aziz, Adnan, et al. Elements of Programming Interviews

In the wait-for graph above, our deadlock detection program will detect at least one cycle and return true.

For this algorithm, we’ll use a slightly different implementation of the directed graph to explore other data structures. We are still implementing it using the adjacency list but instead of an object (map), we’ll store the vertices in an array.

The processes will be modeled as vertices starting with the 0th process. The dependency between the processes will be modeled as edges between the vertices. The edges (adjacent vertices) will be stored in a Linked List, in turn stored at the index that corresponds to the process number.

class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedList { constructor() { this.head = null; } insertAtHead(data) { let temp = new Node(data); temp.next = this.head; this.head = temp; return this; } getHead() { return this.head; } } class Graph { constructor(vertices) { this.vertices = vertices; this.list = []; for (let i=0; i
     

Solution:

  • Every vertex will be assigned 3 different colors: white, gray and black. Initially all vertices will be colored white. When a vertex is being processed, it will be colored gray and after processing black.
  • Use Depth First Search to traverse the graph.
  • If there is an edge from a gray vertex to another gray vertex, we’ve discovered a back edge (a self-loop or an edge that connects to one of its ancestors), hence a cycle is detected.
  • Time Complexity: O(V+E)

Pseudocode:

function isDeadlocked Color all vertices white Run DFS on the vertices 1. Mark current node Gray 2. If adjacent vertex is Gray, return true 3. Mark current node Black Return false
const Colors = { WHITE: 'white', GRAY: 'gray', BLACK: 'black' } Object.freeze(Colors); function isDeadlocked(g) { let color = []; for (let i=0; i
      

Clone Graph

Problem Statement:

Consider a vertex type for a directed graph in which there are two fields: an integer label and a list of references to other vertices. Design an algorithm that takes a reference to a vertex u, and creates a copy of the graph on the vertices reachable from u. Return the copy of u. – Aziz, Adnan, et al. Elements of Programming Interviews

Solution:

  • Maintain a map that maps the original vertex to its counterpart. Copy over the edges.
  • Use BFS to visit the adjacent vertices (edges).
  • Time Complexity: O(n), where n is the total number of nodes.

Pseudocode:

function cloneGraph Initialize an empty map Run BFS Add original vertex as key and clone as value to map Copy over edges if vertices exist in map Return clone
class GraphVertex { constructor(value) { this.value = value; this.edges = []; } } function cloneGraph(g) { if (g == null) { return null; } let vertexMap = {}; let queue = [g]; vertexMap[g] = new GraphVertex(g.value); while (queue.length) { let currentVertex = queue.shift(); currentVertex.edges.forEach(v => { if (!vertexMap[v]) { vertexMap[v] = new GraphVertex(v.value); queue.push(v); } vertexMap[currentVertex].edges.push(vertexMap[v]); }); } return vertexMap[g]; } let n1 = new GraphVertex(1); let n2 = new GraphVertex(2); let n3 = new GraphVertex(3); let n4 = new GraphVertex(4); n1.edges.push(n2, n4); n2.edges.push(n1, n3); n3.edges.push(n2, n4); n4.edges.push(n1, n3); cloneGraph(n1);

Making Wired Connections

Problem Statement:

Design an algorithm that takes a set of pins and a set of wires connecting pairs of pins, and determines if it is possible to place some pins on the left half of a PCB, and the remainder on the right half, such that each wire is between left and right halves. Return such a division, if one exists. – Aziz, Adnan, et al. Elements of Programming Interviews

Solution:

  • Model the set as a graph. The pins are represented by the vertices and the wires connecting them are the edges. We’ll implement the graph using an edge list.

The pairing described in the problem statement is possible only if the vertices (pins) can be divided into “2 independent sets, U and V such that every edge (u,v) either connects a vertex from U to V or a vertex from V to U.” (Source) Such a graph is known as a Bipartite graph.

To check whether the graph is bipartite, we’ll use the graph coloring technique. Since we need two sets of pins, we have to check if the graph is 2-colorable (which we’ll represent as 0 and 1).

Initially, all vertices are uncolored (-1). If adjacent vertices are assigned the same colors, then the graph is not bipartite. It is not possible to assign two colors alternately to a graph with an odd length cycle using 2 colors only, so we can greedily color the graph.

Extra step: We will handle the case of a graph that is not connected. The outer for loop takes care of that by iterating over all the vertices.

  • Time Complexity: O(V+E)

Pseudocode:

function isBipartite 1. Initialize an array to store uncolored vertices 2. Iterate through all vertices one by one 3. Assign one color (0) to the source vertex 4. Use DFS to reach the adjacent vertices 5. Assign the neighbors a different color (1 - current color) 6. Repeat steps 3 to 5 as long as it satisfies the two-colored constraint 7. If a neighbor has the same color as the current vertex, break the loop and return false
function isBipartite(graph) { let color = []; for (let i=0; i
       

Transform one string to another

Problem Statement:

Given a dictionary D and two strings s and f, write a program to determine if s produces t. Assume that all characters are lowercase alphabets. If s does produce f, output the length of a shortest production sequence; otherwise, output -1. – Aziz, Adnan, et al. Elements of Programming Interviews

For example, if the dictionary D is ["hot", "dot", "dog", "lot", "log", "cog"], s is "hit" and t is "cog", the length of the shortest production sequence is 5.

"hit" -> "hot" -> "dot" -> "dog" -> "cog"

Solution:

  • Represent the strings as vertices in an undirected, unweighted graph, with an edge between 2 vertices if the corresponding strings differ in one character at most. We'll implement a function (compareStrings) that calculates the difference in characters between two strings.
  • Piggybacking off the previous example, the vertices in our graph will be
{hit, hot, dot, dog, lot, log, cog}
  • The edges represented by the adjacency list approach we discussed in section 0. Graph Implementation, will be:
{ "hit": ["hot"], "hot": ["dot", "lot"], "dot": ["hot", "dog", "lot"], "dog": ["dot", "lot", "cog"], "lot": ["hot", "dot", "log"], "log": ["dog", "lot", "cog"], "cog": ["dog", "log"] }
  • Once we finish building the graph, the problem boils down to finding the shortest path from a start node to a finish node. This can be naturally computed using Breadth First Search.
  • Time Complexity: O(M x M x N), where M is the length of each word and N is the total number of words in the dictionary.

Pseudocode:

function compareStrings Compare two strings char by char Return how many chars differ function transformString 1. Build graph using compareStrings function. Add edges if and only if the two strings differ by 1 character 2. Run BFS and increment length 3. Return length of production sequence
function transformString(beginWord, endWord, wordList) { let graph = buildGraph(wordList, beginWord); if (!graph.has(endWord)) return 0; let queue = [beginWord]; let visited = {}; visited[beginWord] = true; let count = 1; while (queue.length) { let size = queue.length; for (let i=0; i { if (!visited[neighbor]) { queue.push(neighbor); visited[neighbor] = true; } }) } count++; } return 0; }; function compareStrings (str1, str2) { let diff = 0; for (let i=0; i { graph.set(word, []); wordList.forEach( (nextWord) => { if (compareStrings(word, nextWord) == 1) { graph.get(word).push(nextWord); } }) }) if (!graph.has(beginWord)) { graph.set(beginWord, []); wordList.forEach( (nextWord) => { if (compareStrings(beginWord, nextWord) == 1) { graph.get(beginWord).push(nextWord); } }) } return graph; }

Where to go from here?

Hopefully, by the end of this article, you have realized that the most challenging part in graph problems is identifying how to model the problems as graphs. From there, you can use/modify the two graph traversals to get the expected output.

Other graph algorithms that are nice to have in your toolkit are:

  • Topological Ordering
  • Shortest Path Algorithms (Dijkstra and Floyd Warshall)
  • Minimum Spanning Trees Algorithms (Prim and Kruskal)

If you found this article helpful, consider buying me a coffee. It will keep me awake when I work on a video tutorial of this article :)                                        

References:

Aziz, Adnan, et al. Elements of Programming Interviews. 2nd ed., CreateSpace Independent Publishing Platform, 2012.