AlgoDaily Solution
1var assert = require('assert');
2
3function shortestClearPath(grid) {
4 let m = grid.length;
5 let n = grid[0].length;
6
7 if (grid[0][0] === 1 || grid[m - 1][n - 1] === 1) {
8 return -1;
9 }
10
11 let directions = [
12 [0, 1],
13 [0, -1],
14 [1, 0],
15 [-1, 0],
16 [1, 1],
17 [1, -1],
18 [-1, 1],
19 [-1, -1]
20 ];
21
22 let queue = [
23 [
24 [0, 0], 1
25 ]
26 ];
27 grid[0][0] = 1;
28
29 while (queue.length > 0) {
30 let [cellPosition, pathLength] = queue.shift();
31 let x = cellPosition[0];
32 let y = cellPosition[1];
33
34 if (x === m - 1 && y === n - 1) {
35 return pathLength;
36 }
37
38 // otherwise we have to go 8 directions
39 for (const direction of directions) {
40 let newX = x + direction[0];
41 let newY = y + direction[1];
42
43 // check if we are on valid tile
44 if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] === 0) {
45 queue.push([
46 [newX, newY], pathLength + 1
47 ]);
48 grid[newX][newY] = 1;
49 }
50 }
51 }
52 return -1;
53
54}
55
56
57try {
58 assert.equal(shortestClearPath([
59 [0, 1],
60 [1, 0]
61 ]), 2);
62 console.log('PASSED: ' + "`shortestClearPath([[0,1],[1,0]])` should return `2`");
63} catch (err) {
64 console.log(err);
65}
66
67try {
68 assert.equal(shortestClearPath([
69 [0, 0, 0],
70 [1, 1, 0],
71 [1, 1, 0]
72 ]), 4);
73 console.log('PASSED: ' + "`shortestClearPath([[0,0,0],[1,1,0],[1,1,0]])` should return `4`");
74} catch (err) {
75 console.log(err);
76}
77
78try {
79 assert.equal(shortestClearPath([
80 [1, 0, 0],
81 [1, 1, 0],
82 [1, 1, 0]
83 ]), -1);
84 console.log('PASSED: ' + "`shortestClearPath([[1,0,0],[1,1,0],[1,1,0]])` should return `-1`");
85} catch (err) {
86 console.log(err);
87}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
39
var assert = require('assert');
function shortestClearPath(grid) {
return;
}
try {
assert.equal(shortestClearPath([
[0, 1],
[1, 0]
]), 2);
console.log('PASSED: ' + "`shortestClearPath([[0,1],[1,0]])` should return `2`");
} catch (err) {
console.log(err);
}
try {
assert.equal(shortestClearPath([
[0, 0, 0],
[1, 1, 0],
[1, 1, 0]
]), 4);
console.log('PASSED: ' + "`shortestClearPath([[0,0,0],[1,1,0],[1,1,0]])` should return `4`");
} catch (err) {
console.log(err);
}
OUTPUT
Results will appear here.