-
Notifications
You must be signed in to change notification settings - Fork 0
/
542. 01 Matrix.js
82 lines (61 loc) · 1.89 KB
/
542. 01 Matrix.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import * as Utils from './Utils.js';
/**
* Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
* The distance between two adjacent cells is 1.
*/
class Test {
orthogonalSteps = [
{x: 0, y: -1}, // top
{x: 1, y: 0}, // right
{x: 0, y: 1}, // bottom
{x: -1, y: 0}, // left
]
method(matrix) {
let result = []
for (let i = 0; i < matrix.length; i++) {
if (!result[i])
result[i] = [];
for (let j = 0; j < matrix[i].length; j++) {
result[i][j] = this.calculateDistanceTo0(i, j, matrix);
}
}
return result;
}
calculateDistanceTo0(i, j, matrix) {
const queueOfCoords = [{x: i, y: j}];
while (queueOfCoords.length > 0) {
const coord = queueOfCoords.shift();
if (matrix[coord.x][coord.y] === 0) {
return Math.abs(i - coord.x) + Math.abs(j - coord.y);
}
const adjacentCoords = this.getAdjacentCoords(matrix, coord.x, coord.y)
queueOfCoords.push(...adjacentCoords)
}
return undefined;
}
getAdjacentCoords(matrix, x, y) {
const result = [];
this.orthogonalSteps.forEach(step => {
const neighX = x + step.x;
const neighY = y + step.y;
if (this.isInBound(matrix, neighX, neighY)) {
result.push({x: neighX, y: neighY});
}
})
return result;
}
isInBound(matrix, x, y) {
return x >= 0 && x < matrix.length && y >= 0 && y < matrix[x].length;
}
}
const testExecutor = new Test();
const testCase = [
{par1: [[0,0,0],[0,1,0],[1,1,1]], result: [[0,0,0],[0,1,0],[1,2,1]]},
{par1: [[0,0,0],[0,1,0],[0,0,0]], result: [[0,0,0],[0,1,0],[0,0,0]]},
];
testCase.forEach((testCase, i) => {
console.log(`Executing test n° ${i+1}`, testCase);
const result = testExecutor.method(testCase.par1);
console.log('Result:', result);
console.assert(Utils.matrixAreEquals(testCase.result, result));
})