Graph algorithm in java