# Program to find length of longest possible stick in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a list of integers sticks. Here each element in the list represents a stick with two ends, these values are between 1 and 6. These are representing each end. We can connect two sticks together if any of their ends are same. The resulting stick's ends will be the leftover ends and its length is increased. We have to find the length of the longest stick possible.

So, if the input is like sticks = [ [2, 3], [2, 4], [3, 5], [6, 6] ], then the output will be 3, as we can connect [2, 3] and [2, 4] to get [3, 4], which we can connect it with [3, 5] to get [4, 5].

To solve this, we will follow these steps:

• Define a function dfs() . This will take node, edge_idx, and a set visited

• if edge_idx is not null, then

• if edge_idx is visited, then

• return 0

• mark edge_idx as visited

• res := 0

• for each e_idx in g[node], do

• n_node := sticks[e_idx, 0] when sticks[e_idx, 1] is same as node otherwise sticks[e_idx, 1]

• res := maximum of res and 1 + dfs(n_node, e_idx, visited)

• if edge_idx is non-zero, then

• delete edge_idx from visited

• return res

• From the main method do the following:

• sticks := a list for all s in sticks (s[0], s[1])

• vertices := a new set

• g := an empty map

• for each index i and edge in sticks, do

• insert i into g[edge[0]]

• insert i into g[edge[1]]

• insert edge[0] and edge[1] into vertices

• res := 0

• for each v in vertices, do

• res := maximum of res and dfs(v, null, and empty set)

• return res - 1

Let us see the following implementation to get better understanding:

## Example

Live Demo

from collections import defaultdict

class Solution:
def solve(self, sticks):
def dfs(node, edge_idx, visited):
if edge_idx is not None:
if edge_idx in visited:
return 0
res = 0
for e_idx in g[node]:
n_node = sticks[e_idx][0] if sticks[e_idx][1] == node else sticks[e_idx][1]
res = max(res, 1 + dfs(n_node, e_idx, visited))
if edge_idx:
visited.remove(edge_idx)
return res

sticks = [(s[0], s[1]) for s in sticks]
vertices = set()
g = defaultdict(set)
for i, edge in enumerate(sticks):
res = 0
for v in vertices:
res = max(res, dfs(v, None, set()))
return res - 1

ob = Solution()
sticks = [
[2, 3],
[2, 4],
[3, 5],
[6, 6]
]
print(ob.solve(sticks))



## Input

sticks = [ [2, 3], [2, 4], [3, 5], [6, 6] ]

## Output

3
Published on 10-Nov-2020 08:47:08