Repository navigation
Expand file tree
/
Copy pathGrid.java
More file actions
119 lines (85 loc) · 2.47 KB
/
Copy pathGrid.java
File metadata and controls
119 lines (85 loc) · 2.47 KB
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
import java.util.List;
public class Grid {
private int rows;
private int columns;
private char[][] map;
// Constructor
public Grid(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.map = new char[rows][columns];
initializeMap();
}
// Initialize the grid
private void initializeMap() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
map[i][j] = '.';
}
}
// Start
map[0][0] = 'S';
// Goal
map[9][9] = 'G';
}
// Display normal grid
public void display() {
System.out.println();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
// Check whether position is inside grid
public boolean isValidPosition(int row, int column) {
return row >= 0 &&
row < rows &&
column >= 0 &&
column < columns;
}
// Check obstacle
public boolean isObstacle(int row, int column) {
return map[row][column] == '#';
}
// Add obstacle
public boolean setObstacle(int row, int column) {
if (!isValidPosition(row, column)) {
return false;
}
// Don't allow obstacle on Start or Goal
if (map[row][column] == 'S' ||
map[row][column] == 'G') {
return false;
}
map[row][column] = '#';
return true;
}
// Display calculated A* path
public void displayPath(List<Node> path) {
System.out.println();
// Create a copy of the original map
char[][] pathMap = new char[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
pathMap[i][j] = map[i][j];
}
}
// Put * on calculated path
for (Node node : path) {
if (pathMap[node.row][node.column] == '.') {
pathMap[node.row][node.column] = '*';
}
}
// Print calculated path
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(pathMap[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
}