# 934. 最短的桥

### 实现

``````int flag[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};    // 往4个方向移动
typedef struct Point {
int x;
int y;
} Point;

void getStartPoint(int **A, int ASize, int *AColSize, Point *startPoint)
{
for (int i = 0; i < ASize; i++) {
for (int j = 0; j < AColSize[i]; j++) {
if (A[i][j] == 1) {
startPoint->x = i;
startPoint->y = j;
return;
}
}
}
}

void dfs(int **A, int ASize, int *AColSize, int x, int y)
{
if (x < 0 || x >= ASize || y < 0 || y >= AColSize[x]) {
return;
}
if (A[x][y] != 1) {
return;
}
A[x][y] = 2;
for (int i = 0; i < 4; i++) {
int dx = x + flag[i][0];
int dy = y + flag[i][1];
dfs(A, ASize, AColSize, dx, dy);
}
}

int shortestBridge(int **A, int ASize, int *AColSize)
{
int res = 0;
// 随便找一个小岛上的点(值为1的点)作为起点
Point startPoint = {-1, -1};
getStartPoint(A, ASize, AColSize, &startPoint);

// 从开始处做dfs，把起点所连接的岛的值都变为2
dfs(A, ASize, AColSize, startPoint.x, startPoint.y);

// 模拟队列
int tail = 0;
Point *queue = (Point*)malloc(sizeof(Point) * (ASize * AColSize[0] + 1));
for (int i = 0; i < ASize; i++) {
for (int j = 0; j < AColSize[i]; j++) {
if (A[i][j] == 2) {
queue[tail].x = i;
queue[tail].y = j;
tail++;
}
}
}

// bfs 搜索
int ttmp = tail;
for (int i = htmp; i < ttmp; i++) {
for (int j = 0; j < 4; j++) {
int dx = queue[i].x + flag[j][0];
int dy = queue[i].y + flag[j][1];
if (dx < 0 || dx >= ASize || dy < 0 || dy >= AColSize[dx]) {
continue;
}
if (A[dx][dy] == 2) {
continue;
}
if (A[dx][dy] == 1) {
return res;
}

// A[dx][dy]值为0
queue[tail].x = dx;
queue[tail].y = dy;
tail++;
A[dx][dy] = 2;
}
}
res++;
}

return res;
}
/*
int main()
{
int **a = (int**)malloc(sizeof(int*) * 2);
int *tmp = (int*)malloc(sizeof(int) * 2);
tmp[0] = 0;
tmp[1] = 1;
a[0] = tmp;
int *tmp2 = (int*)malloc(sizeof(int) * 2);
tmp2[0] = 1;
tmp2[1] = 0;
a[1] = tmp2;

int *col = (int*)malloc(sizeof(int) * 2);
col[0] = 2;
col[1] = 2;
printf("%d\n", shortestBridge(a, 2, col));
getchar();
return 0;
}
*/