constdfs=(cur)=>{let res =0;// do some logicfor(const next of graph[cur]){if(seen.has(next))continue;
seen.add(next);
ans +=dfs(next);}return res;};const seen =newSet([START_NODE]);returndfs(START_NODE);
π‘ Tips : Use parent node instead of using [object Object] ([object Object])
constdfs=(cur, parent)=>{if(!cur)return;for(const next of graph[cur]){// Block to move back to parentif(next === parent)continue;// logicdfs(next, cur);}};dfs(0,-1);
β¨ Iterative Algorithm
using stack.
constdfs=(graph)=>{const stack =[START_NODE];const seen =newSet([START_NODE]);let res =0;while(stack.length){const cur = stack.pop();// do some logicfor(const next of graph[cur]){if(seen.has(next))continue;
seen.add(next);
stack.push(next);}}return res;};