Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (() => {
- const dim = 7;
- const graph = {};
- const path = [];
- // create graph
- for (let i = 0; i < dim*dim; i++) {
- const row = i % dim;
- const col = Math.floor(i / dim);
- const edges = [
- getIndex(row + 1, col),
- getIndex(row -1, col),
- getIndex(row, col + 1),
- getIndex(row, col - 1),
- ].filter(e => e != null);
- graph[i] = {
- edges: shuffle(edges),
- };
- }
- // create maze path
- explore(graph, 0);
- console.log('graph:', graph);
- console.log('path:', path);
- function getIndex(row, col) {
- if (row >= dim || row < 0 || col >= dim || col < 0) return null;
- return (col * dim) + row;
- }
- function shuffle(array) {
- for(let i = 0; i < array.length; i++){
- const randomIndex = Math.floor(Math.random() * array.length);
- const temp = array[i];
- array[i] = array[randomIndex];
- array[randomIndex] = temp;
- }
- return array;
- }
- function explore(graph, currentIndex) {
- const current = graph[currentIndex];
- current.visited = true;
- for (let i = 0; i < current.edges.length; i++) {
- const nextIndex = current.edges[i];
- const next = graph[nextIndex];
- if (!next.visited) {
- path.push([currentIndex, nextIndex]);
- explore(graph, nextIndex);
- }
- }
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement