Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic optimizations for UndirectedSparseGraph #130

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions DataStructures/Graphs/UndirectedSparseGraph.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,19 +236,16 @@ public virtual bool RemoveVertex(T vertex)
if (!_adjacencyList.ContainsKey(vertex))
return false;

_adjacencyList.Remove(vertex);

foreach (var adjacent in _adjacencyList)
var neighbors = Neighbours(vertex);
foreach (var neighbor in neighbors)
{
if (adjacent.Value.Contains(vertex))
{
adjacent.Value.Remove(vertex);

// Decrement the edges count.
--_edgesCount;
}
_adjacencyList[neighbor].Remove(vertex);
}

_edgesCount -= neighbors.Count;

_adjacencyList.Remove(vertex);

return true;
}

Expand Down
36 changes: 28 additions & 8 deletions DataStructures/Lists/DLinkedList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -557,14 +557,7 @@ public virtual void Clear()
/// <returns>True if found; false otherwise.</returns>
public virtual bool Contains(T dataItem)
{
try
{
return Find(dataItem).IsEqualTo(dataItem);
}
catch (Exception)
{
return false;
}
return TryFind(dataItem, out var found) && found.IsEqualTo(dataItem);
}

/// <summary>
Expand All @@ -589,6 +582,33 @@ public virtual T Find(T dataItem)
throw new Exception("Item was not found.");
}

/// <summary>
/// Tries to find the specified item in the list.
/// </summary>
/// <param name="dataItem">Value to find.</param>
/// <param name="found">Value if found, default otherwise.</param>
/// <returns>value.</returns>
public virtual bool TryFind(T dataItem, out T found)
{
found = default;

if (IsEmpty()) return false;

var currentNode = _firstNode;
while (currentNode != null)
{
if (currentNode.Data.IsEqualTo(dataItem))
{
found = dataItem;
return true;
}

currentNode = currentNode.Next;
}

return false;
}

/// <summary>
/// Tries to find a match for the predicate. Returns true if found; otherwise false.
/// </summary>
Expand Down