Dijkstra Implementation: Comparing my program with widely available Internet Java program











up vote
1
down vote

favorite












I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation.



On Baeldung and on Vogella (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...



I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is if (!distances.containsKey(thisCity)) { and the else part of it along with Map<City, Integer> distances = new HashMap<>();. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand.



I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help



public int findMinDistance(City src, City dest) {
Set<City> visited = new HashSet<>();

Queue<City> queue = new LinkedList<>();

Map<City, Integer> distances = new HashMap<>();
distances.put(src, Integer.valueOf(0));
visited.add(src);
queue.add(src);

City currentCity;
while (queue.size() != 0) {
currentCity = queue.poll();
Set<City> cities = currentCity.getCityDistancesMap().keySet();
for (City thisCity : cities) {
int thisDistance = distances.get(currentCity).intValue() +
currentCity.getCityDistance(thisCity);
if (!distances.containsKey(thisCity)) {
distances.put(thisCity, thisDistance);
} else {
int oldDistance = distances.get(thisCity).intValue();
if (oldDistance > thisDistance) {
distances.remove(thisCity);
distances.put(thisCity, thisDistance);
}
}
if (!visited.contains(thisCity)) {
visited.add(thisCity);
queue.add(thisCity);
}
}
}
return distances.get(dest);
}









share|improve this question






















  • I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
    – Vogel612
    Nov 26 at 0:08






  • 1




    Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
    – Ketan
    Nov 26 at 1:23












  • I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
    – Ketan
    Nov 26 at 2:53















up vote
1
down vote

favorite












I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation.



On Baeldung and on Vogella (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...



I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is if (!distances.containsKey(thisCity)) { and the else part of it along with Map<City, Integer> distances = new HashMap<>();. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand.



I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help



public int findMinDistance(City src, City dest) {
Set<City> visited = new HashSet<>();

Queue<City> queue = new LinkedList<>();

Map<City, Integer> distances = new HashMap<>();
distances.put(src, Integer.valueOf(0));
visited.add(src);
queue.add(src);

City currentCity;
while (queue.size() != 0) {
currentCity = queue.poll();
Set<City> cities = currentCity.getCityDistancesMap().keySet();
for (City thisCity : cities) {
int thisDistance = distances.get(currentCity).intValue() +
currentCity.getCityDistance(thisCity);
if (!distances.containsKey(thisCity)) {
distances.put(thisCity, thisDistance);
} else {
int oldDistance = distances.get(thisCity).intValue();
if (oldDistance > thisDistance) {
distances.remove(thisCity);
distances.put(thisCity, thisDistance);
}
}
if (!visited.contains(thisCity)) {
visited.add(thisCity);
queue.add(thisCity);
}
}
}
return distances.get(dest);
}









share|improve this question






















  • I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
    – Vogel612
    Nov 26 at 0:08






  • 1




    Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
    – Ketan
    Nov 26 at 1:23












  • I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
    – Ketan
    Nov 26 at 2:53













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation.



On Baeldung and on Vogella (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...



I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is if (!distances.containsKey(thisCity)) { and the else part of it along with Map<City, Integer> distances = new HashMap<>();. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand.



I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help



public int findMinDistance(City src, City dest) {
Set<City> visited = new HashSet<>();

Queue<City> queue = new LinkedList<>();

Map<City, Integer> distances = new HashMap<>();
distances.put(src, Integer.valueOf(0));
visited.add(src);
queue.add(src);

City currentCity;
while (queue.size() != 0) {
currentCity = queue.poll();
Set<City> cities = currentCity.getCityDistancesMap().keySet();
for (City thisCity : cities) {
int thisDistance = distances.get(currentCity).intValue() +
currentCity.getCityDistance(thisCity);
if (!distances.containsKey(thisCity)) {
distances.put(thisCity, thisDistance);
} else {
int oldDistance = distances.get(thisCity).intValue();
if (oldDistance > thisDistance) {
distances.remove(thisCity);
distances.put(thisCity, thisDistance);
}
}
if (!visited.contains(thisCity)) {
visited.add(thisCity);
queue.add(thisCity);
}
}
}
return distances.get(dest);
}









share|improve this question













I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation.



On Baeldung and on Vogella (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...



I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is if (!distances.containsKey(thisCity)) { and the else part of it along with Map<City, Integer> distances = new HashMap<>();. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand.



I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help



public int findMinDistance(City src, City dest) {
Set<City> visited = new HashSet<>();

Queue<City> queue = new LinkedList<>();

Map<City, Integer> distances = new HashMap<>();
distances.put(src, Integer.valueOf(0));
visited.add(src);
queue.add(src);

City currentCity;
while (queue.size() != 0) {
currentCity = queue.poll();
Set<City> cities = currentCity.getCityDistancesMap().keySet();
for (City thisCity : cities) {
int thisDistance = distances.get(currentCity).intValue() +
currentCity.getCityDistance(thisCity);
if (!distances.containsKey(thisCity)) {
distances.put(thisCity, thisDistance);
} else {
int oldDistance = distances.get(thisCity).intValue();
if (oldDistance > thisDistance) {
distances.remove(thisCity);
distances.put(thisCity, thisDistance);
}
}
if (!visited.contains(thisCity)) {
visited.add(thisCity);
queue.add(thisCity);
}
}
}
return distances.get(dest);
}






java algorithm






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 at 23:41









Ketan

61




61












  • I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
    – Vogel612
    Nov 26 at 0:08






  • 1




    Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
    – Ketan
    Nov 26 at 1:23












  • I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
    – Ketan
    Nov 26 at 2:53


















  • I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
    – Vogel612
    Nov 26 at 0:08






  • 1




    Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
    – Ketan
    Nov 26 at 1:23












  • I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
    – Ketan
    Nov 26 at 2:53
















I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
– Vogel612
Nov 26 at 0:08




I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K.
– Vogel612
Nov 26 at 0:08




1




1




Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
– Ketan
Nov 26 at 1:23






Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time...
– Ketan
Nov 26 at 1:23














I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
– Ketan
Nov 26 at 2:53




I had actually tested it for the graph mentioned in this link. baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map
– Ketan
Nov 26 at 2:53















active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208409%2fdijkstra-implementation-comparing-my-program-with-widely-available-internet-jav%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208409%2fdijkstra-implementation-comparing-my-program-with-widely-available-internet-jav%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Сан-Квентин

Алькесар

Josef Freinademetz