DFS using Lambda Function (Simple and Short)


#1

int Solution::solve(int A, vector<vector>& B)
{
vector adj[A + 1];
for(auto b : B)
{
adj[b[0]].push_back(b[1]);
adj[b[1]].push_back(b[0]);
}

vector<int> color(A + 1, 0);
function<bool(int, int)> dfs = [&](int cur, int col)
{
    if(color[cur] != 0) return color[cur] == col;
    
    color[cur] = col;

    for(auto nxt : adj[cur]) 
        if(!dfs(nxt, -col)) return false;

    return true;
};

for(int i = 1; i <= A; i++)
{
    if(color[i] == 0 && !dfs(i, 1)) return 0;
}
return 1;

}