Fish Graph (Codeforces 1818D)
Tags: Implement, dfs and similar

You are given a simple undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $$$1$$$ to $$$n$$$.We define a graph to be a Fish Graph if it contains a simple cycle with a special node $$$u$$$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $$$2$$$ extra edges. Both edges should connect to node $$$u$$$, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph.In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph.  Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph. 

Input: The first line of input contains the integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The description of test cases follows.The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2\,000$$$) — the number of nodes and the number of edges.Each of the next $$$m$$$ lines contains the description of an edge. Each line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i\neq v_i$$$) — an edge connects node $$$u_i$$$ to node $$$v_i$$$.It is guaranteed that no two edges connect the same unordered pair of nodes.Furthermore, it is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases both do not exceed $$$2\,000$$$.

Output: For each testcase, output "YES" if the graph contains a subgraph that is a Fish Graph, otherwise print "NO". If the answer is "YES", on the following lines output a description of the subgraph.The first line of the description contains one integer $$$k$$$ — the number of edges of the subgraph. On the next $$$k$$$ lines, output the edges of the chosen subgraph. Each of the $$$k$$$ lines should contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u, v\le n$$$, $$$u\neq v$$$) — the edge between $$$u$$$ and $$$v$$$ belongs to the subgraph. The order in which $$$u$$$ and $$$v$$$ are printed does not matter, as long as the two nodes are connected by an edge in the original graph. The order in which you print the edges does not matter, as long as the resulting subgraph is a fish graph.If there are multiple solutions, print any.

Note: In the first example, a possible valid subgraph contains the cycle $$$1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1$$$. The special node of this cycle is node $$$4$$$. The two extra edges $$$4 - 5$$$ and $$$4 - 6$$$ are both connected to $$$4$$$, completing the Fish Graph.In the second example, a possible valid subgraph contains the cycle $$$1 \rightarrow 3 \rightarrow 4 \rightarrow 1$$$. The special node of this cycle is node $$$3$$$. The two extra edges $$$3 - 2$$$ and $$$3 - 5$$$ are both connected to $$$3$$$, completing the Fish Graph.In the last example, it can be proven that there is no valid subgraph. 

Sample Inputs:
3
7 8
1 2
2 3
3 4
4 1
4 5
4 6
4 2
6 7
7 7
6 7
1 2
2 3
3 4
4 1
1 3
3 5
4 4
1 3
3 4
4 1
1 2

Sample Outputs:
YES
6
5 4
6 4
4 3
1 4
2 1
3 2
YES
5
5 3
2 3
3 1
4 3
1 4
NO

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def dfs(node):
    for nei in graph[node]:
        if par[nei] == -1:
            par[nei] = node
            (r, arr) = dfs(nei)
            if r:
                return (True, arr)
            par[nei] = -1
        elif nei != par[node]:
            dst = nei
            path = [[node, nei]]
            curr = node
            S = {node, nei}
            while curr != dst:
                S.add(curr)
                path.append([curr, par[curr]])
                curr = par[curr]
            for v in S:
                cnt = 0
                tmp = []
                for nei in graph[v]:
                    if nei not in S:
                        cnt += 1
                        tmp.append([v, nei])
                    if cnt == 2:
                        path.append(tmp[0])
                        path.append(tmp[1])
                        return (True, path)
    vis[node] = True
    return (False, [])
for _ in range(int(input())):
    (n, m) = readInts()
    graph = [[] for _ in range(n)]
    for _ in range(m):
        (u, v) = readInts()
        u -= 1
        v -= 1
        graph[u].append(v)
        graph[v].append(u)
    s = False
    vis = [False] * n
    for i in range(n):
        if len(graph[i]) < 4:
            continue
        if vis[i]:
            continue
        par = [-1] * n
        par[i] = -2
        (s, path) = dfs(i)
        if s:
            print('YES')
            print(len(path))
            for (u, v) in path:
                print(u + 1, v + 1)
            break
    if not s:
        print('NO')

Solution (Python):
from collections import defaultdict
import os, sys, threading
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 9)
ii = lambda : int(input())
mii = lambda : map(int, input().split())
fii = lambda : map(float, input().split())
lmii = lambda : list(map(int, input().split()))
i2c = lambda n: chr(ord('a') + n)
c2i = lambda c: ord(c) - ord('a')

def construct_answer(cycle, node, adj_l, adj_r):
    print(len(cycle) + 2)
    for i in range(len(cycle)):
        print(cycle[i], cycle[(i + 1) % len(cycle)])
    print(node, adj_l)
    print(node, adj_r)

def find_cycle(node, next_node, parents):
    cycles = [node]
    curr = node
    while curr != next_node:
        curr = parents[curr]
        cycles.append(curr)
    return cycles

def dfs(cycles, graph, visited, node, parent, parents):
    visited[node] = True
    parents[node] = parent
    res = False
    for adj in graph[node]:
        if adj == parent:
            continue
        elif visited[adj] is None:
            dfs(cycles, graph, visited, adj, node, parents)
        elif visited[adj]:
            cycles.append((node, adj))
    visited[node] = False
    return None

def solve():
    (n, m) = mii()
    graph = defaultdict(list)
    for _ in range(m):
        (u, v) = mii()
        graph[u].append(v)
        graph[v].append(u)
    visited = [None] * (n + 1)
    parents = [0] * (n + 1)
    cycles = []
    for i in range(1, n + 1):
        if visited[i] is None:
            dfs(cycles, graph, visited, i, 0, parents)
    found = False
    for (node, adj) in cycles:
        cycle = find_cycle(node, adj, parents)
        node_in_cycle = set(cycle)
        for node in cycle:
            if len(graph[node]) <= 3:
                continue
            count = 0
            fish_tail = []
            for node_adj in graph[node]:
                if node_adj not in node_in_cycle:
                    count += 1
                    fish_tail.append(node_adj)
            if count > 1:
                print('YES')
                found = True
                construct_answer(cycle, node, fish_tail[0], fish_tail[1])
                break
        if found:
            break
    if not found:
        print('NO')
t = ii()
for _ in range(t):
    solve()
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

Solution (Python):
for _ in range(int(input())):
    (N, M) = map(int, input().split())
    ed = [set() for _ in range(N)]
    for _ in range(M):
        (u, v) = map(lambda x: int(x) - 1, input().split())
        ed[u].add(v)
        ed[v].add(u)
    fo = False
    for u in range(N):
        ta = ed[u].copy()
        if len(ta) < 4:
            continue
        while len(ta) >= 2:
            st = ta.pop()
            ex = [False for _ in range(N)]
            ex[u] = True
            ex[st] = True
            pi = [st]
            pr = [-1 for _ in range(N)]
            pr[st] = u
            while pi:
                cn = pi.pop()
                for nn in ed[cn]:
                    if ex[nn]:
                        continue
                    pr[nn] = cn
                    if nn in ta:
                        end = nn
                        fo = True
                        break
                    ex[nn] = True
                    pi.append(nn)
                if fo:
                    break
            if fo:
                break
        if fo:
            break
    if not fo:
        print('NO')
        continue
    print('YES')
    ta = ed[u].difference({st, end})
    fe = [(ta.pop(), u), (ta.pop(), u), (u, st), (end, u)]
    cn = end
    pn = pr[end]
    while pn != u:
        fe.append((cn, pn))
        cn = pn
        pn = pr[cn]
    print(len(fe))
    for edge in fe:
        (u, v) = edge
        print(u + 1, v + 1)