【Java开源代码栏目提醒】:网学会员为需要Java开源代码的朋友们搜集整理了BitMapMinDis.java相关资料,希望对各位网友有所帮助!
class BitMap {
// map数组存放位图,table数组存放
// 最短距离的数表
int[][] map, table;
// row存放位图的宽度,col存放位图
// 的长度,cnt存放位图中像素点的
// 总数
int row, col, cnt;
// 构造器
public BitMap(int[][] map, int row, int col) {
// 二维数组存放位图,行数即为位图的宽,列数
// 即为位图的长
this.row = row;
this.col = col;
this.map = new int[row][col];
table = new int[row][col];
// 将测试数据赋给存放位图的map数组
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
this.map[i][j] = map[i][j];
}
// 计算出像素点的总数
cnt = row * col;
}
// 计算每个像素与白像素点的最短距离
public void calDis() {
int i, j, k;
// 找出所有的白像素点
for (i = 0; i < row; i++)
for (j = 0; j < col; j++) {
// 白像素点到自身的距离是0
if (map[i][j] == 1) {
table[i][j] = 0;
cnt--; // 未计算距离的点数量减1
}
// 如果不是白像素点,赋给-1,表示未计算
else {
table[i][j] = -1;
}
}
// 首先查找所有距离白像素点距离为0的点,即从白像素点
// 开始计算,它周围的非白像素点到它的距离都是1
k = 0;
// 当还有点没有计算出距离时继续循环
while (cnt > 0) {
for (i = 0; i < row; i++)
for (j = 0; j < col; j++) {
if (table[i][j] == k) {
// 计算四周的点到最近白色像素的距离
neighbor(i, j, k);
}
}
k++;
}
}
// 计算(i, j)点四周的点都最近白色像素的距离
public void neighbor(int i, int j, int k) {
// 如果不是最上边的点
if (i - 1 >= 0) {
// 上边的点如果还没有被赋值,就赋予k+1
if (table[i-1][j] == -1) {
table[i-1][j] = k + 1;
cnt--;
}
}
// 如果不是最下边的点
if (i + 1 < row) {
// 下边的点如果还没有被赋值,就赋予k+1
if (table[i+1][j] == -1) {
table[i+1][j] = k + 1;
cnt--;
}
}
// 如果不是最左边的点
if (j - 1 >= 0) {
// 左边的点如果还没有被赋值,就赋予k+1
if (table[i][j-1] == -1) {
table[i][j-1] = k + 1;
cnt--;
}
}
// 如果不是最右边的点
if (j + 1 < col ) {
// 右边的点如果还没有被赋值,就赋予k+1
if (table[i][j+1] == -1) {
table[i][j+1] = k + 1;
cnt--;
}
}
}
// 输出位图
public void printBitMap() {
System.out.println("位图:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
// 输出数表
public void printTable() {
System.out.println("最短距离数表:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
// 主类
public class BitMapMinDis {
// 主方法
public static void main(String[] args) {
int[][] map = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0}};
BitMap aTest = new BitMap(map, 3, 4);
aTest.printBitMap();
aTest.calDis();
aTest.printTable();
}
}