Refactored adjacency matrix solution