Category: DFS

Minimize count of steps to make all Matrix elements as 0 by replacing neighbours of K with 0

#include using namespace std;  void traverse(int M, int N,              vector& matrix,              int row, int col){          if (row >= 0 && row < M        && col >= 0 && col < N) {        if (matrix[row][col] == 0) {            return;        }                          matrix[row][col] = 0;                  traverse(M, N, matrix, row, col - 1);                  traverse(M, N, matrix, row, col + 1);                  traverse(M, N, matrix, row - 1, col);                  traverse(M, N, matrix, row + […]

Continue Reading

Maximize difference between pair of nodes in a given rooted tree such that one node is ancestor of another

#include using namespace std;  vector tree;vector visited;vector ancestorNum;  int maxDiff = INT_MIN;  void dfs(int src, int val, vector& W){          visited[src] = true;          for (auto neighbour : tree[src]) {                                  if (!visited[neighbour]            && (ancestorNum[neighbour]                > ancestorNum[src])) {                          maxDiff = max(                val – W[neighbour – 1],                maxDiff);                          dfs(neighbour, val, W);        }    }}  void bfs(int src, int N){            visited.assign(N, false);          queue q;              ancestorNum[src] = 0;          visited[src] = true;          q.push(src);          while (!q.empty()) {                  int cur = q.front();        q.pop();                  for (auto neighbour : tree[cur]) {                                      if […]

Continue Reading

Minimize sum of node values by filling given empty Tree such that each node is GCD of its children

#include using namespace std;  class Node {public:    int val;    Node *left, *right;    Node(int val)    {        this->val = val;        left = NULL;        right = NULL;    }};  class Tree {public:    unordered_map depth;              int findDepth(Node* cur)    {        int mx = 0;        if (cur->left) {            mx = findDepth(cur->left);        }        if (cur->right) {            mx = max(mx, findDepth(cur->right));        }                          return depth[cur] = mx + 1;    }              int dfs(Node* cur, bool flag, int parValue)    {        if (parValue != -1) {            if (flag)                cur->val = parValue;            else                cur->val = parValue * 2;        }        int […]

Continue Reading

Sum of all nodes with smaller values at a distance K from a given node in a BST

  #include using namespace std;  struct TreeNode {      int data;    TreeNode* left;    TreeNode* right;          TreeNode(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }};  void kDistanceDownSum(TreeNode* root,                      int k, int& sum){          if (root == NULL || k < 0)        return;          if (k == 0) {        sum += root->data;        return;    }              kDistanceDownSum(root->left,                     k – 1, sum);    kDistanceDownSum(root->right,                     k – 1, sum);}  int kDistanceSum(TreeNode* root,                 int target,                 int k, int& sum){        if (root == NULL)        return -1;          if (root->data == target) {        kDistanceDownSum(root->left,                         k – […]

Continue Reading

Print all the paths from root to leaf, with a specified sum in Binary tree

  import java.util.*;  class GFG {      static List result        = new ArrayList();          static class Node {        int data;        Node left, right;    };          static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = temp.right = null;        return temp;    }              static void pathSumUtil(        Node node, int targetSum,        Stack stack)    {        if (node == null) {            return;        }        stack.push(node.data);          if (node.left == null            && node.right == null) {            if (node.data == targetSum) {                result.add(new ArrayList(stack));            }        }        pathSumUtil(node.left,                    targetSum – node.data,                    stack);        pathSumUtil(node.right,                    targetSum – node.data,                    stack);        stack.pop();    }              static List […]

Continue Reading

Find all the Mother Vertices of a graph

  #include using namespace std;  void dfs_helper(int u,                vector& adj,                bool visited[]){    if (visited[u])        return;      visited[u] = true;      for (auto v : adj[u]) {        if (!visited[v])            dfs_helper(v, adj, visited);    }}  void getTransposeGraph(    vector& adj,    vector& trans_adj){    for (int u = 0; u < adj.size(); u++) {        for (auto v : adj[u]) {            trans_adj[v].push_back(u);        }    }}  void initialize_visited(bool visited[], int n){    for (int u = 0; u < n; u++)        visited[u] = false;}  vector findAllMotherVertices(    vector& adj){    int n = adj.size();    bool […]

Continue Reading

Kth largest element in an N-array Tree

  #include using namespace std;  class Node {public:    int data;    vector childs;};  int largestELe = INT_MIN;  void largestEleUnderRange(    Node* root, int data){            if (root->data < data) {        largestELe = max(root->data,                         largestELe);    }          for (Node* child : root->childs) {                  largestEleUnderRange(child, data);    }}  void KthLargestElement(Node* root,                       int K){            int ans = INT_MAX;          for (int i = 0; i < K; i++) {                                  largestEleUnderRange(root, ans);                          ans = largestELe;        largestELe = INT_MIN;    }          cout data = data;          return temp;}  int main(){                                        Node* root = newNode(10);    (root->childs).push_back(newNode(2));    (root->childs).push_back(newNode(34));    (root->childs).push_back(newNode(56));    (root->childs).push_back(newNode(100));    (root->childs[0]->childs).push_back(newNode(77));    (root->childs[0]->childs).push_back(newNode(88));    (root->childs[2]->childs).push_back(newNode(1));    (root->childs[3]->childs).push_back(newNode(7));    (root->childs[3]->childs).push_back(newNode(8));    (root->childs[3]->childs).push_back(newNode(9));      int […]

Continue Reading

Minimum time required to color all edges of a Tree

  #include using namespace std;  int ans = 0;  vector edges[100000];  void Add_edge(int u, int v){    edges[u].push_back(v);    edges[v].push_back(u);}  void minTimeToColor(int node, int parent,                    int arrival_time){            int current_time = 0;      for (auto x : edges[node]) {                  if (x != parent) {                                      ++current_time;                                      if (current_time == arrival_time)                ++current_time;                          ans = max(ans, current_time);                                      minTimeToColor(x, node, current_time);        }    }}  int main(){      pair A[] = { { 1, 2 },                            { 2, 3 },                            { 3, 4 } };      for (auto i : […]

Continue Reading

Find the Dominators for every vertex in a given DAG (Directed Acyclic Graph)

#include using namespace std;  vector b(100);  int vis[100] = {};  void findDominator(vector graph,                   bitset par, int node){        if (vis[node] == 0) {                b[node] = ~b[node];                  vis[node] = 1;    }              b[node] &= par;              b[node][node] = 1;          for (int i = 0; i < (int)graph[node].size(); i++) {                                findDominator(graph, b[node], graph[node][i]);    }}  void buildGraph(vector adj, int E, int V){            vector graph(V + 1);          for (int i = 0; i < E; i++) {        graph[adj[i].first].push_back(adj[i].second);    }          bitset g;              g[0] […]

Continue Reading