1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
|
package tp7;
import tp7.WeightedGraph.Edge;
import tp7.WeightedGraph.Graph;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.HashSet;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;
//Classe pour gérer l'affichage
class Board extends JComponent
{
private static final long serialVersionUID = 1L;
Graph graph;
int pixelSize;
int ncols;
int nlines;
HashMap<Integer, String> colors;
int start;
int end;
double max_distance;
int current;
LinkedList<Integer> path;
public Board(Graph graph, int pixelSize, int ncols, int nlines, HashMap<Integer, String> colors, int start, int end)
{
super();
this.graph = graph;
this.pixelSize = pixelSize;
this.ncols = ncols;
this.nlines = nlines;
this.colors = colors;
this.start = start;
this.end = end;
this.max_distance = ncols * nlines;
this.current = -1;
this.path = null;
}
//Mise à jour de l'affichage
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Ugly clear of the frame
g2.setColor(Color.cyan);
g2.fill(new Rectangle2D.Double(0,0,this.ncols*this.pixelSize, this.nlines*this.pixelSize));
int num_case = 0;
for (WeightedGraph.Vertex v : this.graph.vertexlist)
{
double type = v.indivTime;
int i = num_case / this.ncols;
int j = num_case % this.ncols;
if (colors.get((int)type).equals("green"))
g2.setPaint(Color.green);
if (colors.get((int)type).equals("gray"))
g2.setPaint(Color.gray);
if (colors.get((int)type).equals("blue"))
g2.setPaint(Color.blue);
if (colors.get((int)type).equals("yellow"))
g2.setPaint(Color.yellow);
g2.fill(new Rectangle2D.Double(j*this.pixelSize, i*this.pixelSize, this.pixelSize, this.pixelSize));
if (num_case == this.current)
{
g2.setPaint(Color.red);
g2.draw(new Ellipse2D.Double(j*this.pixelSize+this.pixelSize/2, i*this.pixelSize+this.pixelSize/2, 6, 6));
}
if (num_case == this.start)
{
g2.setPaint(Color.white);
g2.fill(new Ellipse2D.Double(j*this.pixelSize+this.pixelSize/2, i*this.pixelSize+this.pixelSize/2, 4, 4));
}
if (num_case == this.end)
{
g2.setPaint(Color.black);
g2.fill(new Ellipse2D.Double(j*this.pixelSize+this.pixelSize/2, i*this.pixelSize+this.pixelSize/2, 4, 4));
}
num_case += 1;
}
num_case = 0;
for (WeightedGraph.Vertex v : this.graph.vertexlist)
{
int i = num_case / this.ncols;
int j = num_case % this.ncols;
if (v.timeFromSource < Double.POSITIVE_INFINITY)
{
float g_value = (float) (1 - v.timeFromSource / this.max_distance);
if (g_value < 0)
g_value = 0;
g2.setPaint(new Color(g_value, g_value, g_value));
g2.fill(new Ellipse2D.Double(j*this.pixelSize+this.pixelSize/2, i*this.pixelSize+this.pixelSize/2, 4, 4));
WeightedGraph.Vertex previous = v.prev;
if (previous != null)
{
int i2 = previous.num / this.ncols;
int j2 = previous.num % this.ncols;
g2.setPaint(Color.black);
g2.draw(new Line2D.Double(j * this.pixelSize + this.pixelSize/2, i * this.pixelSize + this.pixelSize/2, j2 * this.pixelSize + this.pixelSize/2, i2 * this.pixelSize + this.pixelSize/2));
}
}
num_case += 1;
}
int prev = -1;
if (this.path != null)
{
g2.setStroke(new BasicStroke(3.0f));
for (int cur : this.path)
{
if (prev != -1)
{
g2.setPaint(Color.red);
int i = prev / this.ncols;
int j = prev % this.ncols;
int i2 = cur / this.ncols;
int j2 = cur % this.ncols;
g2.draw(new Line2D.Double(j * this.pixelSize + this.pixelSize/2, i * this.pixelSize + this.pixelSize/2, j2 * this.pixelSize + this.pixelSize/2, i2 * this.pixelSize + this.pixelSize/2));
}
prev = cur;
}
}
}
//Mise à jour du graphe (à appeler avant de mettre à jour l'affichage)
public void update(Graph graph, int current)
{
this.graph = graph;
this.current = current;
repaint();
}
//Indiquer le chemin (pour affichage)
public void addPath(Graph graph, LinkedList<Integer> path)
{
this.graph = graph;
this.path = path;
this.current = -1;
repaint();
}
}
//Classe principale. C'est ici que vous devez faire les modifications
public class App {
//Initialise l'affichage
private static void drawBoard(Board board, int nlines, int ncols, int pixelSize)
{
JFrame window = new JFrame("Plus court chemin");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(0, 0, ncols*pixelSize+20, nlines*pixelSize+40);
window.getContentPane().add(board);
window.setVisible(true);
}
//Méthode A*
//graph: le graphe représentant la carte
//start: un entier représentant la case de départ
// (entier unique correspondant à la case obtenue dans le sens de la lecture)
//end: un entier représentant la case d'arrivée
// (entier unique correspondant à la case obtenue dans le sens de la lecture)
//ncols: le nombre de colonnes dans la carte
//numberV: le nombre de cases dans la carte
//board: l'affichage
//retourne une liste d'entiers correspondant au chemin.
private static LinkedList<Integer> AStar(Graph graph, int start, int end, int ncols, int numberV, Board board)
{
graph.vertexlist.get(start).timeFromSource=0;
int number_tries = 0;
//TODO: mettre tous les noeuds du graphe dans la liste des noeuds à visiter:
HashSet<Integer> to_visit = new HashSet<Integer>();
//TODO: Remplir l'attribut graph.vertexlist.get(v).heuristic pour tous les noeuds v du graphe:
while (to_visit.contains(end))
{
//TODO: trouver le noeud min_v parmis tous les noeuds v ayant la distance temporaire
// (graph.vertexlist.get(v).timeFromSource + heuristic) minimale.
int min_V = findMin_V(di);
//On l'enlève des noeuds à visiter
to_visit.remove(min_V );
number_tries += 1;
//TODO: pour tous ses voisins, on vérifie si on est plus rapide en passant par ce noeud.
for (int i = 0; i < graph.vertexlist.get(min_V(0, 0)).adjacencylist.size(); i++)
{
int to_try = graph.vertexlist.get(min_V(0, 0)).adjacencylist.get(i).destination;
//A completer
}
//On met à jour l'affichage
try {
board.update(graph, min_V);
Thread.sleep(10);
} catch(InterruptedException e) {
System.out.println("stop");
}
}
System.out.println("Done! Using A*:");
System.out.println(" Number of nodes explored: " + number_tries);
System.out.println(" Total time of the path: " + graph.vertexlist.get(end).timeFromSource);
LinkedList<Integer> path=new LinkedList<Integer>();
path.addFirst(end);
//TODO: remplir la liste path avec le chemin
board.addPath(graph, path);
return path;
}
//Méthode Dijkstra
//graph: le graphe représentant la carte
//start: un entier représentant la case de départ
// (entier unique correspondant à la case obtenue dans le sens de la lecture)
//end: un entier représentant la case d'arrivée
// (entier unique correspondant à la case obtenue dans le sens de la lecture)
//numberV: le nombre de cases dans la carte
//board: l'affichage
//retourne une liste d'entiers correspondant au chemin.
private static LinkedList<Integer> Dijkstra(Graph graph, int start, int end, int numberV, Board board)
{
graph.vertexlist.get(start).timeFromSource=0;
int number_tries = 0;
//TODO: mettre tous les noeuds du graphe dans la liste des noeuds à visiter:
HashSet<Integer> to_visit = new HashSet<Integer>();
while (to_visit.contains(end))
{
//TODO: trouver le noeud min_v parmis tous les noeuds v ayant la distance temporaire
// graph.vertexlist.get(v).timeFromSource minimale.
//On l'enlève des noeuds à visiter
//get vertex with min dist
to_visit.remove(min_V);
number_tries += 1;
//TODO: pour tous ses voisins, on vérifie si on est plus rapide en passant par ce noeud.
for (int i = 0; i < graph.vertexlist.get(min_V(0, 0)).adjacencylist.size(); i++)
{
int to_try = graph.vertexlist.get(min_V(0, 0)).adjacencylist.get(i).destination;
//A completer
}
//On met à jour l'affichage
try {
board.update(graph, min_V(0, 0));
Thread.sleep(10);
} catch(InterruptedException e) {
System.out.println("stop");
}
}
System.out.println("Done! Using Dijkstra:");
System.out.println(" Number of nodes explored: " + number_tries);
System.out.println(" Total time of the path: " + graph.vertexlist.get(end).timeFromSource);
LinkedList<Integer> path=new LinkedList<Integer>();
path.addFirst(end);
//TODO: remplir la liste path avec le chemin
board.addPath(graph, path);
return path;
}
//Méthode principale
public static void main(String[] args) {
//Lecture de la carte et création du graphe
try {
//TODO: obtenir le fichier qui décrit la carte
File myObj = new File("??.txt");
Scanner myReader = new Scanner(myObj);
String data = "";
//On ignore les deux premières lignes
for (int i=0; i < 3; i++)
data = myReader.nextLine();
//Lecture du nombre de lignes
int nlines = Integer.parseInt(data.split("=")[1]);
//Et du nombre de colonnes
data = myReader.nextLine();
int ncols = Integer.parseInt(data.split("=")[1]);
//Initialisation du graphe
Graph graph = new Graph();
HashMap<String, Integer> groundTypes = new HashMap<String, Integer>();
HashMap<Integer, String> groundColor = new HashMap<Integer, String>();
data = myReader.nextLine();
data = myReader.nextLine();
//Lire les différents types de cases
while (!data.equals("==Graph=="))
{
String name = data.split("=")[0];
int time = Integer.parseInt(data.split("=")[1]);
data = myReader.nextLine();
String color = data;
groundTypes.put(name, time);
groundColor.put(time, color);
data = myReader.nextLine();
}
//On ajoute les sommets dans le graphe (avec le bon type)
for (int line=0; line < nlines; line++)
{
data = myReader.nextLine();
for (int col=0; col < ncols; col++)
{
graph.addVertex(groundTypes.get(String.valueOf(data.charAt(col))));
}
}
//TODO: ajouter les arrêtes
for (int line=0; line < nlines; line++)
{
for (int col=0; col < ncols; col++)
{
int source = line*ncols+col;
int dest;
double weight;
//On donne la première arrête
if (line > 0)
{
if (col > 0)
{
dest = (line - 1)*ncols+col - 1;
weight = //A completer
graph.addEgde(source, dest, weight);
}
//A completer
}
//A completer
}
}
//On obtient les noeuds de départ et d'arrivé
data = myReader.nextLine();
data = myReader.nextLine();
int startV = Integer.parseInt(data.split("=")[1].split(",")[0]) * ncols + Integer.parseInt(data.split("=")[1].split(",")[1]);
data = myReader.nextLine();
int endV = Integer.parseInt(data.split("=")[1].split(",")[0]) * ncols + Integer.parseInt(data.split("=")[1].split(",")[1]);
myReader.close();
//A changer pour avoir un affichage plus ou moins grand
int pixelSize = 10;
Board board = new Board(graph, pixelSize, ncols, nlines, groundColor, startV, endV);
drawBoard(board, nlines, ncols, pixelSize);
board.repaint();
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("stop");
}
//On appelle Dijkstra
LinkedList<Integer> path = Dijkstra(graph, startV, endV, nlines*ncols, board);
//TODO: laisser le choix entre Dijkstra et A*
//Écriture du chemin dans un fichier de sortie
try {
File file = new File("out.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i: path)
{
bw.write(String.valueOf(i));
bw.write('\n');
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
WeightedGraph.java |
Partager