グラフ・DFSメニュー【連結の判定・グラフ全体の連結の判定・連結成分の数・連結成分の大きさ】
【連結の判定】コード
reader.on('close', () => {
const dfs = (now, seen) => {
if (now === t - 1) {
connect = true;
return;
}
const nexts = list[now];
for (const next of nexts) {
if (!seen.includes(next)) {
dfs(next, [...seen, next]);
}
}
};
const [n, s, t] = lines.shift().split(' ').map(Number);
const list = new Array(n).fill().map(e => []);
for (let i = 0; i < n; i++) {
const v = Number(lines.shift());
const a = lines.shift().split(' ').map(e => e - 1);
list[i] = a;
}
let connect = false;
// console.table(list);
dfs(s - 1, [s - 1]);
console.log(connect ? 'Yes' : 'No');
});
うp。
【グラフ全体の連結の判定】コード
reader.on('close', () => {
const dfs = (now, seen) => {
seen[now] = true;
if (!seen.includes(false)) {
connect = true;
return;
}
const nexts = list[now];
for (const next of nexts) {
if (!seen[next]) {
dfs(next, seen);
}
}
};
const n = Number(lines.shift());
const list = new Array(n).fill().map(e => []);
for (let i = 0; i < n; i++) {
const v = Number(lines.shift());
const a = lines.shift().split(' ').map(e => e - 1);
list[i] = a;
}
let connect = false;
dfs(0, new Array(n).fill(false));
console.log(connect ? 'Yes' : 'No');
});
うp。
Task
【連結成分の数】コード
reader.on('close', () => {
const dfs = (now, seen) => {
seen[now] = true;
const nexts = list[now];
for (const next of nexts) {
if (!seen[next]) {
dfs(next, seen);
}
}
};
const n = Number(lines.shift());
const list = new Array(n).fill().map(e => []);
for (let i = 0; i < n; i++) {
const v = Number(lines.shift());
const a = lines.shift().split(' ').map(e => e - 1);
list[i] = a;
}
let connect_num = 0;
const seen = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
if (!seen[i]) {
connect_num++;
dfs(i, seen);
}
}
dfs(0, new Array(n).fill(false));
console.log(connect_num);
});
うp。
【連結成分の大きさ】コード
reader.on('close', () => {
const dfs = (now, seen) => {
seen[now] = true;
size++;
// console.log(1, size);
const nexts = list[now];
for (const next of nexts) {
if (!seen[next]) {
dfs(next, seen);
}
}
};
const [n, k] = lines.shift().split(' ').map(Number);
const list = new Array(n).fill().map(e => []);
for (let i = 0; i < n; i++) {
const v = Number(lines.shift());
const a = lines.shift().split(' ').map(e => e - 1);
list[i] = a;
}
// console.table(list);
let under_k = true;
const seen = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
size = 0;
if (!seen[i]) {
dfs(i, seen);
if (size > k) {
under_k = false;
break;
}
}
}
console.log(under_k ? 'Yes' : 'No');
});
うp。
コメント