##Very Positive Aspects of the Code
- Many of the comments are meaningful.
- Many of the routine names are descriptive.
##Basic Comments
- The assumption that the graph is undirected is mistaken:
Each segment of river is listed as pairs of addresses, from upstream to downstream. 2. In my opinion trying to define a graph based on nodes is a poor starting point. See my comments here and here. 3. Thinking about problems mathematically and writing a specification before writing code is recommended by at least one Turing Award winner.
##Decoupling It would be helpful to separate the business logic abstractions of Peggy and Sam and swimming, from the underlying mathematical abstractions of graphs and nodes upon which the business logic is built. Both the business logic and the mathematics should be separated from raw Java arrays and lists etc.
###Modularity
Decoupling the code provides natural module boundaries. Node.java
is a step in this direction, but more separation of abstractions would be beneficial.
#Program Specification
###Summary of Problem
- The Map is given as a directed graph from upstream to downstream.
- A list of vertices which must be avoided is given.
- Peggy Piranha swims only downstream.
- Sam Salmon swims only upstream.
- Find the set of vertices reachable by both Peggy and Sam.
###Given:
- a digraph
Map = {V, E}
(vertices are implied). - a list of dead vertices
dead
- a list of Peggy starting vertices
peggyStart
- a list of Sam starting vertices
samStart
###1. Initialize:
- Create digraph
G
by removing all edgesu -> v
such thatdead.member(u) || dead.member(v) == TRUE
- Create digraph
G'
such that for each edgeu -> v
inG
there is an edgev -> u
inG'
.
###2. Find strongly connected components:
peggyPaths
= the set of strongly connected components inG
containing at least one element ofpeggyStart
.samPaths
= the strongly connected component inG'
containing at least one element ofsamStart
.
###3. Find the set of common vertices:
peggyCanReach
= the union of all vertices inpeggyPaths
.samCanReach
= the union of all vertices insamPaths
.return intersection (peggyCanReach, samCanReach)
##Implementation Details Finding the strongly connected components of a digraph can be done in linear time [O(n + m)] using Kosaraju's Algorithm.
- 2.7k
- 13
- 23