/
MapGenerator.java
123 lines (110 loc) · 3.09 KB
/
MapGenerator.java
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
import java.util.Random;
import java.util.Arrays;
public class MapGenerator
{
public static void main(String args[])
{
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
boolean[][] map = generateMap(width, height, p);
while(true)
{
if(isConnected(map))
{
break;
}
else
{
// p += .01;
map = generateMap(width, height, p);
}
}
System.out.println(height);
System.out.println(width);
printMap(map);
}
public static void printMap(boolean[][] map)
{
for(int r = 0; r < map.length; r++)
{
for(int c = 0; c < map[r].length; c++)
{
System.out.print((map[r][c] ? "0" : "1"));
if(c != map[r].length - 1)
{
System.out.print(",");
}
}
System.out.println();
}
}
public static boolean isConnected(boolean[][] map)
{
int numOpenSpots = 0;
int firstR = -1;
int firstC = -1;
for(int r = 0; r < map.length; r++)
{
for(int c = 0; c < map[r].length; c++)
{
if(map[r][c])
{
if(firstR == -1 && firstC == -1)
{
firstR = r;
firstC = c;
}
numOpenSpots++;
}
}
}
if(firstR == -1 || firstC == -1)
{
return false;
}
boolean[][] seen = new boolean[map.length][map[0].length];
seen[firstR][firstC] = true;
int found = DFS(map, firstR, firstC, seen);
return found == numOpenSpots;
}
public static int DFS(boolean[][] map, int r, int c, boolean seen[][])
{
int count = 1;
for(int dR = -1; dR < 2; dR += 1)
{
for(int dC = -1; dC < 2; dC += 1)
{
if(Math.abs(dR) == Math.abs(dC))
{
continue;
}
if(r + dR > -1 && r + dR < map.length && c + dC > -1 && c + dC < map[r].length)
{
if(map[r + dR][c + dC] && !seen[r + dR][c + dC])
{
seen[r + dR][c + dC] = true;
count += DFS(map, r + dR, c + dC, seen);
}
}
}
}
return count;
}
public static boolean[][] generateMap(int width, int height, double p)
{
boolean[][] map = new boolean[height][width];
Random rand = new Random();
for(int r = 0; r < map.length; r++)
{
for(int c = 0; c < map[r].length; c++)
{
if(rand.nextDouble() < p)
{
map[r][c] = true;
}
}
}
return map;
}
}