-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMazeData.java
More file actions
84 lines (66 loc) · 2.19 KB
/
MazeData.java
File metadata and controls
84 lines (66 loc) · 2.19 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
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class MazeData {
// 迷宫的高和宽(行和列)
private int N, M;
// 迷宫
private char[][] maze;
public MazeData(String filename) {
if (filename == null)
throw new IllegalArgumentException("Filename can not be null!");
Scanner scanner = null;
try {
File file = new File(filename);
if (!file.exists())
throw new IllegalArgumentException("File " + filename + " doesn't exist!");
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");
// 读取第一行
String nmline = scanner.nextLine();
String[] nm = nmline.trim().split("\\s+");
N = Integer.parseInt(nm[0]);
M = Integer.parseInt(nm[1]);
maze = new char[N][M];
for (int i = 0; i < N; i++) {
String line = scanner.nextLine();
// 每行保证有M个字符
if (line.length() != M)
throw new IllegalArgumentException("Maze file " + filename + " is invalid");
for (int j = 0; j < M; j++) {
maze[i][j] = line.charAt(j);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (scanner != null)
scanner.close();
}
}
public int N() {
return N;
}
public int M() {
return M;
}
public char getMaze(int i, int j) {
if (!inArea(i, j))
throw new IllegalArgumentException("i or j is out of index in getMaze!");
return maze[i][j];
}
public boolean inArea(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < M;
}
public void print() {
System.out.println(N + " " + M);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
System.out.print(maze[i][j]);
}
System.out.println();
}
}
}