AcWing 847. 图中点的层次 ( JavaScript )
原题链接
简单
作者:
gaobowen
,
2019-12-05 09:41:30
,
所有人可见
,
阅读 940
let val = new Int32Array(200010);
let idx = 0;
let next = new Int32Array(200010);
let head = new Int32Array(100010).fill(-1);
let add = (a, b) => {
val[idx] = b;
next[idx] = head[a];
head[a] = idx++;
}
let used = new Int32Array(100010);
let bfs = (x, y) => {
let queue = [x];
let step = -1;
while (queue.length > 0) {
step++;
let nextStep = [];
for (let i = 0; i < queue.length; i++) {
used[queue[i]] = 1;
if(queue[i] === y) return step;
for (let j = head[queue[i]]; j != -1; j = next[j]) {
if (!used[val[j]]) nextStep.push(val[j]);
}
}
queue = nextStep;
}
return -1;
}
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
let n = 0, m = 0;
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
m = getInputNums(line)[1];
} else {
let arr = getInputNums(line);
add(arr[0], arr[1]);
if (lineIdx === m) {
console.log(bfs(1, n));
}
}
});
});