Use hash to store graph to improve complexity; Some refactoring