简体   繁体   中英

What is the best way to store multiple cities with distances in Java?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM