Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function createMap(string) {
- return string.split('\n').map(row => row.split(''));
- }
- function createGraph(map) {
- const graph = {}
- function linkNode(i,j, cost, dist) {
- return { i, j, cost, dist, dir };
- }
- function slide(startI, startJ, dir) {
- let dist = 0;
- let cost = 1;
- let stopI, stopJ;
- switch(dir) {
- case 'u':
- for (let i = startI; i >= 0; i--) {
- dist++;
- if(i === 0 || map[i][startJ] === 'x') [stopI, stopJ] = [i, startJ];
- if(map[i][startJ] === '#') [dist, stopI, stopJ] = [dist-1, i+1, startJ];
- }
- break;
- case 'd':
- for (let i = startI; i < map.length; i++) {
- dist++;
- if(i === map.length-1 || map[i][startJ] === 'x') [stopI, stopJ] = [i, startJ];
- if(map[i][startJ] === '#') [dist, stopI, stopJ] = [dist-1, i-1, startJ];
- }
- break;
- case 'r':
- for (let j = startJ; j < map[0].length; j++) {
- dist++;
- if(j === map[0].length-1 || map[startI][j] === 'x') [stopI, stopJ] = [startI, j];
- if(map[startI][j] === '#') [dist, stopI, stopJ] = [dist-1, startI, j-1];
- }
- break;
- case 'l':
- for (let j = startJ; j >= 0; j--) {
- dist++;
- if(j === 0 || map[startI][j] === 'x') [stopI, stopJ] = [startI, j];
- if(map[startI][j] === '#') [dist, stopI, stopJ] = [dist-1, startI, j+1];
- }
- break;
- }
- return {
- i: stopI,
- j: stopJ,
- cost, dist, dir
- };
- }
- function createNode(i, j) {
- const node = []
- //up
- if (i !== 0 && map[i-1][j] !== '#') {
- if (map[i][j] === ' ') node.push(slide(i, j, 'u'));
- node.push(linkNode(i-1, j, 1, 1, 'u'));
- }
- //down
- if (i !== map.length-1 && map[i+1][j] !== '#') {
- if (map[i][j] === ' ') node.push(slide(i, j, 'd'));
- node.push(linkNode(i+1, j, 1, 1, 'd'));
- }
- //right
- if (j !== map[0].length-1 && map[i][j+1] !== '#') {
- if (map[i][j] === ' ') node.push(slide(i, j, 'r'));
- node.push(linkNode(i, j+1, 1, 1, 'r'));
- }
- //left
- if (j !== 0 && map[i][j-1] !== '#') {
- if (map[i][j] === ' ') node.push(slide(i, j, 'l'));
- node.push(linkNode(i, j-1, 1, 1, 'l'));
- }
- }
- for (let i = 0; i < map.length; i++) {
- for (let j = 0; j < map[0].length; j++) {
- if (map[i][j] === '#') continue;
- graph[`${i},${j}`] = createNode(i, j);
- }
- }
- return graph;
- }
- function IceMazeSolver(str) {
- const map = createMap(str);
- const graph = createGraph(map);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement