Imports System
Imports System.Collections.Generic
Class CommonElementMatrix
Public Shared Function FindCommonElementInMatrixRows(ByVal matrix As Integer(,)) As Integer
Dim map As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)()
Dim rows As Integer = matrix.GetLength(0)
Dim cols As Integer = matrix.GetLength(1)
For i As Integer = 0 To rows - 1
map(matrix(i, 0)) = If(map.ContainsKey(matrix(i, 0)), map(matrix(i, 0)) + 1, 1)
For j As Integer = 1 To cols - 1
If matrix(i, j) <> matrix(i, j - 1) Then
Dim val As Integer = matrix(i, j)
map(val) = If(map.ContainsKey(val), map(val) + 1, 1)
End If
Next
Next
For Each entry In map
If entry.Value = rows Then
Return entry.Key
End If
Next
Return -1
End Function
Public Shared Sub Main()
Dim matrix As Integer(,) = New Integer(,) {
{1, 2, 3, 5, 36},
{4, 5, 7, 9, 10},
{5, 6, 8, 9, 18},
{1, 3, 5, 8, 24}}
Dim result As Integer = FindCommonElementInMatrixRows(matrix)
If result <> -1 Then
Console.WriteLine("Common element in all rows: " & result)
Else
Console.WriteLine("No common element found in all rows.")
End If
End Sub
End Class
' run:
'
' Common element in all rows: 5
'