算法--广度搜索之金属熔化
求金属熔化所需单位时间
单位时间内若金属方块有2面与溶液接触则可熔化
容器周边一圈为缝隙,金属在缝隙之内
金属内部可能存在空气
input
1
11
0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0 0
0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 0 0 1 1 0 0 0
0 0 0 1 0 0 1 0 0 0 0
0 0 0 1 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0
0 0 1 0 0 1 1 0 0 0 0
0 0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
output
#1 3
code
#include <stdio.h>
struct node {
int x;
int y;
int step;
};
struct node queue[1000];
int table[50][50];
int visit[50][50];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int N, step,result;
void markLiquor(int head, int tail, int value) {
int i, nx, ny;
while (head < tail) {
for (i = 0; i < 4; i++) {
nx = queue[head].x + dir[i][0];
ny = queue[head].y + dir[i][1];
if (nx >= 0 && nx < N && ny >= 0 && ny < N) {
if (table[nx][ny] == 0) {
queue[tail].x = nx;
queue[tail].y = ny;
table[nx][ny] = value;
tail++;
}
}
}
head++;
}
}
bool isMeltable(int x, int y, int noCheckVale) {
int i, nx, ny, num = 0;
if (table[x][y] != 1) {
return false;
}
for (i = 0; i < 4; i++) {
nx = x + dir[i][0];
ny = y + dir[i][1];
if (nx >= 0 && nx < N && ny >= 0 && ny < N) {
if (table[nx][ny] < 0 && table[nx][ny] != noCheckVale) {
num++;
}
}
}
if (num >= 2) {
return true;
}
return false;
}
void printtable() {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (table[i][j] >= 0) {
printf("%d,", table[i][j]);
} else {
printf("-,");
}
}
printf("\r\n");
}
printf("------------------\r\n");
}
int main() {
int T, t, i, j;
int head, tail;
scanf("%d", &T);
for (t = 1; t <= T; t++) {
scanf("%d", &N);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
scanf("%d", &table[i][j]);
visit[i][j] = 0;
}
}
result = 0;
// 1.填充溶液,由于边缘一圈空,故可设0,0为起点
head = tail = 0;
queue[tail].x = 0;
queue[tail].y = 0;
tail++;
step = -1;
table[0][0] = step;
markLiquor(head, tail, step);
printf("首次填充溶液\r\n");
printtable();
// 2.寻找熔化金属加入队列
while (1) {
head = tail = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (isMeltable(i, j, step - 1)) {
queue[tail].x = i;
queue[tail].y = j;
//熔化该金属,标记该金属在此step下熔化
table[i][j] = step - 1;
tail++;
}
}
}
//全部都已熔化则退出
if (tail == 0) {
break;
} else{
result++;
}
printf("熔化金属\r\n");
printtable();
markLiquor(head, tail, step--);
printf("溶液流动刷新\r\n");
printtable();
}
printf("#%d %d\r\n", T, result);
}
return 0;
}
debug
1
11
0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0 0
0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 0 0 1 1 0 0 0
0 0 0 1 0 0 1 0 0 0 0
0 0 0 1 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0
0 0 1 0 0 1 1 0 0 0 0
0 0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
首次填充溶液
-,-,-,-,-,-,-,-,-,-,-,
-,-,1,1,-,-,-,-,-,-,-,
-,-,1,1,1,1,1,1,-,-,-,
-,-,-,1,0,0,1,1,-,-,-,
-,-,-,1,0,0,1,-,-,-,-,
-,-,-,1,1,1,1,1,-,-,-,
-,-,-,-,-,-,-,-,-,-,-,
-,1,1,1,1,1,-,-,-,-,-,
-,-,1,0,0,1,1,-,-,-,-,
-,-,-,1,1,1,1,-,-,-,-,
-,-,-,-,-,-,-,-,-,-,-,
------------------
熔化金属
-,-,-,-,-,-,-,-,-,-,-,
-,-,-,-,-,-,-,-,-,-,-,
-,-,-,1,1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