-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathD8FlowDirection.java
More file actions
79 lines (67 loc) · 3.21 KB
/
Copy pathD8FlowDirection.java
File metadata and controls
79 lines (67 loc) · 3.21 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
package heyingzhe;
public class D8FlowDirection {
// 定义流向编码
private static final int[] FLOW_DIRECTIONS = {1, 2, 4, 8, 16, 32, 64, 128}; // 右、右下、下、左下、左、左上、上、右上
// 计算流向
public static int[][] calculateFlowDirection(int[][] dem) {
int rows = dem.length;
int cols = dem[0].length;
int[][] flowDirection = new int[rows][cols];
// 初始化流向数组,先默认都没有流向
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
flowDirection[i][j] = 0; // 初始流向为0
}
}
// 遍历每个点
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dem[i][j] != -9999 && flowDirection[i][j] == 0) { // 只有在不是缺失值且没有流向的情况下,才计算流向
flowDirection[i][j] = calculateCellFlow(i, j, dem, flowDirection);
}
}
}
return flowDirection;
}
// 计算单个点的流向
private static int calculateCellFlow(int i, int j, int[][] dem, int[][] flowDirection) {
int rows = dem.length;
int cols = dem[0].length;
int minSlope = Integer.MAX_VALUE; // 使用整数类型来存储最小坡度
int flowDir = 0;
int ni = -1, nj = -1;
// 遍历8个邻域
for (int k = 0; k < 8; k++) {
int x = i + (k == 1 || k == 2 || k == 3 ? 1 : (k == 5 || k == 6 || k == 7 ? -1 : 0));
int y = j + (k == 3 || k == 4 || k == 5 ? 1 : (k == 0 || k == 1 || k == 7 ? -1 : 0));
// 如果邻域在有效范围内,且不是缺失值
if (x >= 0 && x < rows && y >= 0 && y < cols && dem[x][y] != -9999) {
int slope = dem[i][j] - dem[x][y]; // 计算坡度差
if (slope > 0 && slope < minSlope) { // 如果坡度差大于0且小于当前最小坡度
minSlope = slope;
flowDir = FLOW_DIRECTIONS[k]; // 更新流向
ni = x;
nj = y;
}
}
}
// 如果没有找到流向(说明周围没有比当前点海拔低的邻域)
if (flowDir == 0) {
// 如果该点周围海拔相同,则选择一个邻域进行流向计算
for (int k = 0; k < 8; k++) {
int x = i + (k == 1 || k == 2 || k == 3 ? 1 : (k == 5 || k == 6 || k == 7 ? -1 : 0));
int y = j + (k == 3 || k == 4 || k == 5 ? 1 : (k == 0 || k == 1 || k == 7 ? -1 : 0));
// 确保邻域在有效范围内,且海拔不为缺失值
if (x >= 0 && x < rows && y >= 0 && y < cols && dem[x][y] != -9999 && dem[i][j] == dem[x][y]) {
// 如果海拔相等,就选择流向已经计算的邻域流向
if (flowDirection[x][y] != 0) {
flowDir = flowDirection[x][y];
break;
}
}
}
}
// 最后返回该点的流向
return flowDir;
}
}