Files
2025-02-22 03:37:47 -07:00

76 lines
2.5 KiB
JavaScript

export function spider(ns) {
var serversSeen = ['home']
for (var i = 0; i < serversSeen.length; i++) {
var thisScan = ns.scan(serversSeen[i]);
for (var j = 0; j < thisScan.length; j++) {
if (serversSeen.indexOf(thisScan[j]) === -1) {
serversSeen.push(thisScan[j]);
}
}
}
return serversSeen;
}
/** @param {NS} ns */
export function find(root, target, path, ns) {
// Add the current node to the path *before* exploring connections.
path.push(root);
if (root === target) {
return path; // Return the complete path
}
var connections = ns.scan(root);
if (!connections || connections.length == 0) {
// IMPORTANT: Remove the current node from the path if it's a dead end.
path.pop();
return null;
}
for (const c of connections) {
if (c !== "home") { // Assuming you want to exclude "home"
// *** CYCLE DETECTION ***
// Check if the connected node is already in the current path.
if (path.includes(c)) {
continue; // Skip this connection to avoid the cycle.
}
// Recursively search from the connected node.
// Pass a *copy* of the path to avoid side effects. Crucially important!
const result = find(c, target, [...path], ns); // ...path creates a copy
if (result) { // Check for a successful path (no need for result.length > 0)
// We don't need to add root here, it was already added at the beginning.
return result; // Return the successful path found by the recursive call.
}
}
}
// If no path was found from any connection, remove the current node from the path.
path.pop(); // Backtrack: Remove the current node
return null;
}
// Example usage (assuming this is in a .js file in Bitburner)
export async function main(ns) {
const target = ns.args[0]; // Get the target server from arguments
if (!target) {
ns.tprint("Usage: run find_path.js <target_server>");
return;
}
const path = [];
const result = find("home", target, path, ns); // Start the search from "home"
if (result) {
ns.tprint("Path found:");
ns.tprint(result.join(" -> ")); // Display the path
var command = "";
result.forEach(function(p) {
command += "connect " + p + ";";
});
navigator.clipboard.writeText(command);
} else {
ns.tprint("No path found to " + target);
}
}