.
This commit is contained in:
18
grid.js
18
grid.js
@@ -26,12 +26,10 @@ class Grid {
|
||||
return this.mapMut((_, pt) => arr[pt.y][pt.x])
|
||||
}
|
||||
|
||||
fillFromStr(str) { return this.fillFromArr(str.split("\n")) }
|
||||
fillFromStr(str, sep = "") { return this.fillFromArr(str.split("\n").map((line) => line.split(sep)) }
|
||||
|
||||
static fromStr(str) {
|
||||
let arr = str.split("\n")
|
||||
return new Grid(arr[0].length, arr.length).fillFromArr(arr)
|
||||
}
|
||||
static fromArr(arr) { return new Grid(arr[0].length, arr.length).fillFromArr(arr) }
|
||||
static fromStr(str, sep = "") { return Grid.fromArr(str.split("\n").map((line) => line.split(sep)) }
|
||||
|
||||
get(pt) {
|
||||
if (this.contains(pt)) {
|
||||
@@ -99,7 +97,7 @@ class Grid {
|
||||
static BFS_STOP = 1
|
||||
static BFS_END = 2
|
||||
|
||||
bfs(pt, func, limit = 1000) {
|
||||
bfs(pt, func, neighbors = "getAdjNeighborsThat", getlimit = 1000) {
|
||||
let visited = [].pt
|
||||
let toVisit = [pt].pt
|
||||
let count = 0
|
||||
@@ -116,7 +114,7 @@ class Grid {
|
||||
let result = func(this.get(toVisit[i]), toVisit[i], this, visited);
|
||||
|
||||
if (result == Grid.BFS_CONTINUE) {
|
||||
newToVisit.pushUniq(...this.getAdjNeighborsThat(toVisit[i], (pt) => !pt.isIn(visited)).map((pt) => (pt.path = [...toVisit[i].path, pt], pt)))
|
||||
newToVisit.pushUniq(...this[neighbors](toVisit[i], (pt) => !pt.isIn(visited)).map((pt) => (pt.path = [...toVisit[i].path, pt], pt)))
|
||||
}
|
||||
|
||||
if (result == Grid.BFS_END) {
|
||||
@@ -178,6 +176,12 @@ class Grid {
|
||||
]
|
||||
}
|
||||
|
||||
toGraph(neighbors = "getAdjNeighbors", cxn = (node, cxnNode) => node.addCxn(cxnNode, cxnNode.val)) {
|
||||
this.mapMut((e) => new Node(e))
|
||||
this.forEach((e, pt) => this[neighbors](pt).forEach((pt) => cxn(e, this.get(pt))))
|
||||
return
|
||||
}
|
||||
|
||||
copy() { return new Grid(this.width, this.height).mapMut((_, pt) => this.get(pt).copyDeep()) }
|
||||
toString(sep = "\t", ...pts) { return this.data.map((r, y) => r.map((e, x) => new Point(x, y).isIn(pts) ? "P" : e).join(sep)).join("\n") }
|
||||
print(sep = "\t", ...pts) { console.log(this.toString(sep, pts)) }
|
||||
|
||||
Reference in New Issue
Block a user