标签:
/* *POJ 3026 Borg Maze *题意: *从S处开始搜索 每遇到A 便会分裂 分裂出来的会继续搜索 *问最终所走的最小步数和 */ /* *思路: *首先BFS所有A或S 求任意两点之间的距离 构建dist数组 *求dist的最小生成树 */ #include <cstdio> #include <cstring> #include <queue> using namespace std; #define INF 1000 int mark, n; int map[55][55]; //存储地图及节点的编号 int lowcost[101]; //合并标记 int dist[101][101]; //邻接矩阵 bool visit[55][55]; //BFS 访问标记 int col, row; struct Point { int x, y; int step; }; int dir[4][2] = { {0, 1}, {1, 0}, {0, -1}, { -1, 0} }; bool isOk(int x, int y) { if (x >= 0 && x <= row && y >= 0 && y <= col) { return true; } return false; } void bfs(int x, int y) { Point p; p.x = x; p.y = y; p.step = 0; memset(visit, false, sizeof(visit)); queue<Point> q; q.push(p); visit[x][y] = true; int count = 1; while (!q.empty()) { Point now = q.front(); q.pop(); Point next; for (int i = 0; i < 4; i++) { next.x = now.x + dir[i][0]; next.y = now.y + dir[i][1]; if (isOk(next.x, next.y) && map[next.x][next.y] >= 0 && !visit[next.x][next.y]) { next.step = now.step + 1; visit[next.x][next.y] = true; q.push(next); if (map[next.x][next.y] > 0) { int u = map[x][y]; int v = map[next.x][next.y]; dist[u - 1][v - 1] = next.step; count ++; if (count == n) { return ; } } } } } } void prim() { int i, j; int sum = 0; mark = 0; lowcost[0] = -1; for (i = 1; i < n; i++) { lowcost[i] = dist[0][i]; } for (i = 1; i < n ; i++) { int min = INF; for (j = 0; j < n; j++) { if (lowcost[j] != -1 && lowcost[j] < min) { min = lowcost[j]; mark = j; } } sum += min; lowcost[mark] = -1; for (j = 0; j < n; j++) { if (dist[mark][j] < lowcost[j]) { lowcost[j] = dist[mark][j]; } } } printf("%d\n", sum); } int main() { int T; int i, j; scanf("%d", &T); while (T--) { n = 0; memset(dist, 0, sizeof(dist)); scanf("%d %d", &col, &row); char c = ‘ ‘; while (c != ‘\n‘) { c = getchar(); } for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { scanf("%c", &c); if (c == ‘S‘ || c == ‘A‘) { map[i][j] = ++n; } else if (c == ‘#‘) { map[i][j] = -1; } else if (c == ‘ ‘) { map[i][j] = 0; } } getchar(); } for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (map[i][j]) { bfs(i, j); } } } prim(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/subrshk/p/4243210.html