Grid

class Grid(val width: Int, val height: Int, initWithDatalessTiles: Boolean = false, isWeighted: Boolean = false) : BaseGraph<Tile>

The Grid class is a specialized graph class.

It uses the data class: Tile(val x: Int, val y: Int, var data: Any? = null) to represent nodes of any datatype, where each node also has x and y coordinates.

The grid can be created in two ways:

  • By specifying a width and height, optionally initializing it with tiles that has data=null.

  • By passing a list of strings, where each string represents a row, and all strings must have the same length.

The Grid class supports the same algorithms as the Graph class. Additionally, it provides methods for connecting nodes in the grid without explicitly adding edges:

  • .connectGridDefault() connects each node to its neighbors in the up, down, left, and right directions, if they exist.

  • .connectGrid(::yourCustomFunction) (or .connectGrid { yourLambda }) allows custom connections, where the function takes a Tile and returns a List<Tile> to connect to.

Example usage:

val grid = Grid(100,100,true)
grid.connectGridDefault()
grid.bfs(Tile(50,50))
grid.visualizeGrid()

String constructor and custom connections example usage:

val stringList = listOf(
"0#4",
"123",
"234"
)
val grid = Grid(stringList)
grid.deleteNodesWithData('#')
grid.connectGrid { t ->
grid.getStraightNeighbours(t).filter { it.x >= t.x || it.y > t.y } // connect right and down
}
grid.bfs(Tile(0, 0, 'S'))
grid.visualizeGrid()

Parameters

width

The width of the grid (number of columns).

height

The height of the grid (number of rows).

initWithDatalessTiles

If true, initializes the grid with empty tiles.

isWeighted

Indicates whether the grid uses weighted or unweighted edges.

Constructors

Link copied to clipboard
constructor(width: Int, height: Int, initWithDatalessTiles: Boolean = false, isWeighted: Boolean = false)
constructor(stringGrid: List<String>)

Construct the grid from a list of strings, where each string represents a row in the grid.

Properties

Link copied to clipboard
val height: Int
Link copied to clipboard
val width: Int

Functions

Link copied to clipboard
fun addEdge(node1: Tile, node2: Tile, weight: Number?)

Adds an edge between two nodes in the graph, and creates the nodes if they don't exist.

Link copied to clipboard
open override fun addNode(node: Tile)

Adds the given node to the graph

Link copied to clipboard
fun bfs(startNode: Tile, target: Tile?, reset: Boolean)

Overload of fun bfs(startNodes: List, target: T?, reset: Boolean) that accepts a single starting node istead of a list

fun bfs(startNodes: List<Tile>, target: Tile?, reset: Boolean)

Performs a Breadth-First Search, which finds the shortest path from the starting node to all other nodes, assuming the graph is unweighted (all edges have a weight of 1.0) It stores results that can be retrieved with the following functions:

Link copied to clipboard
fun connect(node1: Tile, node2: Tile, weight: Number?)

Connects two nodes in the graph, by calling addEdge(node1,node2, weight) and addEdge(node2, node1, weight)

Link copied to clipboard
fun connectGrid(bidirectional: Boolean = false, getNeighbours: (t: Tile) -> List<Tile>)

Connects all nodes in the grid with their neighbors, using a user-defined function to determine the neighbors.

Link copied to clipboard

Connects all nodes in the grid with their straight neighbours, i.e. top, down, left, right neighbours, if they exist within the grid boundaries and are not deleted.

Link copied to clipboard

Retrieves a list of all visited nodes on the order they were visited during the last search operation (DFS, BFS, Dijkstra).

Link copied to clipboard
fun deleteNodeAtXY(x: Int, y: Int)

Deletes the node at the specified (x, y) coordinates in the grid.

Link copied to clipboard
fun deleteNodesWithData(data: Any?)

Deletes all nodes in the grid that have the specified data. Deleted nodes are not considered neighbours of nodes.

Link copied to clipboard
fun depth(): Int

Retrieves the depth of the graph from the most recent search operation

Link copied to clipboard
fun dfs(startNode: Tile, reset: Boolean)

Performs a Depth-First Search on the graph which finds all nodes that's reachable from the starting node it. It stores results that can be retrieved with the following functions:

Link copied to clipboard
fun dijkstra(startNode: Tile, target: Tile?)

Performs Dijkstra's algorithm, which finds the shortest path from the starting node to all other nodes. It stores results that can be retrieved with the following functions:

Link copied to clipboard
fun distanceFromUtoV(u: Tile, v: Tile): Double

Retrieves the shortest distance between two nodes in the graph.

Link copied to clipboard
fun distanceTo(node: Tile): Double

Retrieves the distance to the specified node from the starting node of the most recent search operation (BFS, Dijkstra).

Link copied to clipboard
fun edges(t: Tile): List<Pair<Double, Tile>>

Retrieves a list of edges connected to the specified node.

Link copied to clipboard
fun finalPath(): List<Tile>

Retrieves the shortest path from the start to target node path during the most recent search operation (DFS, BFS, Dijkstra)

Link copied to clipboard

Executes the Floyd-Warshall algorithm on the graph to compute the shortest paths between all pairs of nodes.

Link copied to clipboard
fun foundTarget(): Boolean

Checks if the target node was found during the most recent search operation (BFS, Dijkstra).

Link copied to clipboard

Retrieves the node that is the farthest from the starting node in the most recent search operation (BFS, Dijkstra).

Link copied to clipboard
fun getAllNeighbours(t: Tile): List<Tile>

Retrieves all neighbors (both straight and diagonal) of the given tile.

Link copied to clipboard

Retrieves the diagonal neighbors of the given tile.

Link copied to clipboard
fun getPath(target: Tile): List<Tile>

Retrieves the path from the starting node to the specified target node based on the most recent search results.

Link copied to clipboard

Retrieves the straight (orthogonal) neighbors of the given tile.

Link copied to clipboard
fun maxDistance(): Double

Retrieves the maximum distance from the starting node to any other node of the most recent search operation (BFS, Dijkstra).

Link copied to clipboard
fun minimumSpanningTree(): Pair<Double, Graph>

Computes the Minimum Spanning Tree (MST) of the graph using Prim's algorithm.

Link copied to clipboard
fun neighbours(t: Tile): List<Tile>

Retrieves a list the neighboring nodes of the specified node.

Link copied to clipboard
open override fun nodes(): List<Tile>
Link copied to clipboard
fun print(isWeighted: Boolean)

Prints the graph's adjacency list to the standard error stream.

fun print()

Print the content of the grid, tile by tile

Link copied to clipboard
fun removeEdge(node1: Tile, node2: Tile)

Removes the edge(s) between two nodes in the graph.

Link copied to clipboard

Clears the search results stored in the graph.

Link copied to clipboard
fun size(): Int
Link copied to clipboard
open override fun stronglyConnectedComponents(): List<List<Tile>>

Identifies groups where each node is reachable from every other node in the group.

Link copied to clipboard
open override fun topologicalSort(): List<Tile>

Builds an order of nodes so that the first nodes has no outgoing edges, then nodes with edges pointing to these and so on, assuming the graph is a Directed Acyclic Graph (DAG). This is done by running a DFS from each node and ordering the nodes by descending depth (post-order).

Link copied to clipboard
fun visitedNodes(): List<Tile>

Retrieves a (unordered) list of all visited nodes during any non-reset search operation (DFS, BFS, Dijkstra).

Link copied to clipboard
fun <T : Any> BaseGraph<T>.visualizeGraph(bidirectional: Boolean = false, finalPath: List<T> = finalPath(), screenTitle: String = "Graph visualizer (Click or space to pause and resume)", animationTicTimeOverride: Double? = null, closeOnEnd: Boolean = false, startPaused: Boolean = false, screenWidthOverride: Double? = null)

Visualizes the graph with Bruno Silva's JavaFXSmartGraph library.

Link copied to clipboard
fun Grid.visualizeGrid(currentVisitedNodes: List<Tile> = currentVisitedNodes(), finalPath: List<Tile> = finalPath(), nodeDistances: List<Double> = currentVisitedNodes.map { distanceTo(it) }, screenTitle: String = "Grid visualizer (Click or space to pause and resume)", animationTicTimeOverride: Double? = null, closeOnEnd: Boolean = false, startPaused: Boolean = false, screenWidthOverride: Double? = null)

Visualizes the grid and optionally its traversal process using a graphical interface.

Link copied to clipboard
fun xy2Node(x: Int, y: Int): Tile?

Retrieves the Tile node at the specified (x, y) coordinates, if it exists.