0

I have to write a program that finds the shortest distance. I'm have a hard time figuring out whats the best way to store the data I have. I have a directed graph with the following cities : San Francisco, Houston, Charleston,New Orleans,Baton rouge,Denver,Pittsburgh,Memphis,Las Vegas,Seattle. Listed below are the cities with their edges and distance from the cities. So From Columbus to Miami is 61 miles. Any suggestion on how to store it ?

Columbus ---> Miami:61, Charleston:408, Las Vegas:689

Miami ---> San Francisco:34, Columbus:61

San Francisco ---> Miami, Houston:485

Houston ---> San Francisco, Memphis:63, Denver:83

Charleston ---> Pittsburgh:36, Memphis:86, Seattle:933, Columbus

Rubii
  • 1
  • 3
  • Define a `Node` class which has 2 attributes: a city (String) and a list of `Edges`. Define an `Edge` class which has 2 attributes: a city (String) and distance to it (int) – c0der Oct 27 '20 at 04:34

1 Answers1

0

Have you thought about making a 2d array? Put all the names in the top row and first column, say, String distance[8][8];, then sort of like a multiplication table you would manually enter in the values for the distances. After that, if you wanted to find the distance between Columbus and Miami, you'd just write: System.out.println(distance[Columbus][Miami]);

This is, however, a pretty basic way to store it, so if you find a more comprehensive way, such as making a Cities class, for example, I'd recommend you follow it. Just as a little example of that, you could make a

Public Class Cities() {
public String CityName;
public int distance; }

and then manually making several city objects, as well as setting their distance to different cities. Then, if you wanted to find the distance from one city to another, you could just print out the distance variable with the respective cities, using a custom method.

Ben Kluger
  • 82
  • 6
  • I read somewhere that data in a two-dimensional array is always of the same data type. So i didn't think that was the best fit. – Rubii Oct 27 '20 at 03:46
  • Fair enough. However, it would be easy to store the entire array as a String array (I mistakenly wrote "int" array), and then store the distances as string numbers. Then, when you want to access the values as numbers, just Integer parseInt(distance[...][...]);, and you should get your answer in an int format. If you don't want to use an array, try building a cities class, like I showed above? – Ben Kluger Oct 27 '20 at 04:25