Geeksforgeeks

Error

×

Leaderboard

Showing:

Handle | Score |
---|---|

@Ibrahim Nash | 5725 |

@blackshadows | 5685 |

@akhayrutdinov | 5111 |

@mb1973 | 4989 |

@Quandray | 4908 |

@saiujwal13083 | 4156 |

@sanjay05 | 3762 |

@marius_valentin_dragoi | 3511 |

@sushant_a | 3453 |

@KshamaGupta | 3318 |

@the_coder95 | 3302 |

Complete Leaderboard | |

Handle | Score |

@avaiesshaik782 | 786 |

@arpitsatnalika | 777 |

@tujhekya | 602 |

@prakharxyz | 601 |

@code_it_ | 591 |

@iamronak | 505 |

@imnm | 500 |

@pradeepkumarjad | 488 |

@satyam0460 | 481 |

@nitesha125 | 468 |

@Rahul Jadhav 1 | 466 |

Complete Leaderboard |

Given a Undirected Graph. Check whether it contains a cycle or not.

**Input:**

The first line of the input contains an integer **'T'** denoting the number of test cases. Then **'T'** testcases follow. Each testcase consists of two lines. Description of testcases are as follows: The First line of each testcase contains two integers **'N' and 'M' **which denotes the no of vertices and no of edges respectively. The Second line of each test case contains **'M' ** space separated pairs **u** and **v** denoting that there is a bidirectional edge from **u** to **v** .

**Output:**

The method should return **1** if there is a cycle else it should return **0**.

**User task:**

You don't need to read input or print anything. Your task is to complete the function **isCyclic **which takes the Graph and the number of vertices as inputs and returns true if the given undirected graph contains any cycle. Else, it returns false.

**Expected Time Complexity: **O(V + E).

**Expected Auxiliary Space: **O(V).

**Constraints:**

1 <= T <= 100

2 <= N <= 10^{4}

1 <= M <= (N*(N-1))/2

0 <= u, v <= N-1

Graph doesn't contain multiple edges and self loops.

**Example:
Input:**

3

2 1

0 1

4 3

0 1 1 2 2 3

5 4

0 1 2 3 3 4 4 2

**Output:**

0

0

1

**Explanation:
Testcase 1:** There is a graph with 2 vertices and 1 edge from 0 to 1. So there is no cycle.

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes
Detect cycle in an undirected graph

...

Please choose 'ReadOnlyMode' if you needn't to 'Edit' the problem e.g. viewing OJ's solution, TestCase Files (TCFs), TimeLimit etc.