# 27. 最小矩阵宽度
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function containsAll(mx, left, right, nums) {
const countMap = new Map();
nums.forEach(num => {
countMap.set(num, (count.get(num) || 0) + 1);
});
for(let i=0; i<mx.length; i++) {
for(let j=left; j<=right; j++) {
if (countMap.has(mx[i][j])) {
countMap.set(mx[i][j], countMap.get(mx[i][j]) - 1);
if(countMap.get(mx[i][j] === 0)) {
countMap.delete(mx[i][j]);
}
}
}
}
return countMap.size === 0;
}
function find(mx, nums) {
let minWidth = Infinity;
for(let left=0; left<mx[0].length; left++) {
for(let right=left; right<mx[0].length; right++) {
if(containsAll(mx, left, right, nums)) {
minWidth = Math.min(minWidth, right-left+1);
}
}
}
return minWidth === Infinity ? -1 : minWidth;
}
const input = [];
rl.on('line', (line) => {
input.push(line);
if (input.length === parseInt(input[0].split(' ')[0]) + 3) {
const [N, M] = input[0].split(' ').map(Number);
const mx = input.slice(1, N + 1).map(row => row.split('').map(Number));
const nums = input[input.length - 1].split(' ').map(Number);
console.log(find(mx, nums));
}
});
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
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