(백준) 다리 만들기 (BFS / DFS)

Run Settings
LanguageC
Language Version
Run Command
#include <stdio.h> #define MAX 100 #define INFI 9999999 typedef struct _Pos { int x; int y; int c; } Pos; Pos pos[INFI]; int front = -1, rear = -1; int number = 1; int map[MAX][MAX]; int visited[MAX][MAX]; int px[] = {-1, 1, 0, 0}; int py[] = {0, 0, -1, 1}; void initVisitedMap () { for (int y = 0; y < MAX; y++) { for (int x = 0; x < MAX; x++) { visited[y][x] = 0; } } } void setLandNumber (int x, int y, int n, int limit) { map[y][x] = n; visited[y][x] = 1; for (int i = 0; i < 4; i++) { int newX = x + px[i]; int newY = y + py[i]; if (newX < 0 || newX >= limit || newY < 0 || newY >= limit) { continue; } if (!visited[newY][newX] && map[newY][newX] > 0) { setLandNumber(newX, newY, n, limit); } } } int getMinLandCost (int n, int limit) { int min = INFI; for (int y = 0; y < limit; y++) { for (int x = 0; x < limit; x++) { if (map[y][x] == n) { rear++; pos[rear].x = x; pos[rear].y = y; pos[rear].c = 0; } } } while (front < rear) { front++; int x = pos[front].x; int y = pos[front].y; int c = pos[front].c; for (int i = 0; i < 4; i++) { int newX = x + px[i]; int newY = y + py[i]; if (newX < 0 || newX >= limit || newY < 0 || newY >= limit) { continue; } if (map[newY][newX] != 0 && map[newY][newX] != n) { if (min > c) { min = c; break; } } else if (map[newY][newX] == 0 && !visited[newY][newX]) { rear++; pos[rear].x = newX; pos[rear].y = newY; pos[rear].c = newC + 1; visited[newY][newX] = 1; } } } return min; } int main(void) { int N = 0; int Min = INFI; scanf("%d", &N); for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { scanf("%d", &map[y][x]); } } for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { if (map[y][x] > 0 && !visited[y][x]) { setLandNumber(x, y, number, N); number++; } } } initVisitedMap(); for (int i = 0; i < number; i++) { int minPath = getMinLandCost(i + 1, N); if (Min > minPath) { Min = minPath; } rear = -1; front = -1; initVisitedMap(); } printf("%d\n", (Min == INFI) ? 0 : Min); return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines