Skip to content

Latest commit

ย 

History

History
170 lines (116 loc) ยท 3.49 KB

Dijkstra.md

File metadata and controls

170 lines (116 loc) ยท 3.49 KB

Dijkstra ์ตœ๋‹จ๊ฒฝ๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ•˜๋‚˜์˜ ์‹œ์ž‘ ์ •์ ์—์„œ ๋‹ค๋ฅธ ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๋ฌธ์ œ

  • ๊ฐ€์ค‘์น˜ ์ธ์ ‘ํ–‰๋ ฌ๊ณผ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค
  • ๊ฐ€์ค‘์น˜๊ฐ€ ์–‘์˜ ์ •์ˆ˜์ผ ๋•Œ๋งŒ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค



  • ์ง‘ํ•ฉ S: ์‹œ์ž‘ ์ •์  v๋กœ๋ถ€ํ„ฐ์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๊ฐ€ ์ด๋ฏธ ๋ฐœ๊ฒฌ๋œ ์ •์ ๋“ค์˜ ์ง‘ํ•ฉ
  • ๋ฐฐ์—ด distance: ์ตœ๋‹จ๊ฒฝ๋กœ๊ฐ€ ์•Œ๋ ค์ง„ ์ •์ ๋“ค๋งŒ์„ ์ด์šฉํ•œ ๋‹ค๋ฅธ ์ •์ ๋“ค๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ ๊ธธ์ด

๋งค ๋‹จ๊ณ„์—์„œ ๊ฐ€์žฅ distance ๊ฐ’์ด ์ž‘์€ ์ •์ ์„ ์ง‘ํ•ฉ S์— ์ถ”๊ฐ€



  1. ๊ฐ ๋‹จ๊ณ„์—์„œ ์ง‘ํ•ฉ S์•ˆ์— ์—†๋Š” ์ •์  ์ค‘์—์„œ ๊ฐ€์žฅ distance ๊ฐ’์ด ์ž‘์€ ์ •์ ์„ S์— ์ถ”๊ฐ€ํ•œ๋‹ค.
  2. ์ •์  w๋ฅผ ๊ฑฐ์ณ ์ •์  u๋กœ ๊ฐ€๋Š” ๊ฐ€์ƒ์ ์ธ ๋” ์งง์€ ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž.
  3. ์ •์  v->u์˜ ๊ฑฐ๋ฆฌ๋Š” ์ •์  v->w๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ(2)์™€ ์ •์  w->u๋กœ ๊ฐ€๋Š” ๊ฑฐ๋ฆฌ(3)์„ ํ•ฉํ•œ ๊ฐ’์ด ๋œ๋‹ค.
  4. ํ˜„์žฌ distance ๊ฐ’์ด ๊ฐ€์žฅ ์ž‘์€ ์ •์ ์€ u์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฝ๋กœ 2๋Š” ๊ฒฝ๋กœ 1๋ณด๋‹ค ํ•ญ์ƒ ๊ธธ ์ˆ˜ ๋ฐ–์— ์—†๋‹ค.


์ƒˆ๋กœ์šด ์ •์ ์ด S์— ์ถ”๊ฐ€๋˜๋ฉด distance ๊ฐ’ ๊ฐฑ์‹ 

distance[w] = min(distance[w], distance[u] + weight[u][w])


Dijkstra ์˜ˆ์ œ1



Dijkstra ์˜ˆ์ œ 2

pseudocode


C code

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define TRUE 1
#define FALSE 0
#define MAX_VERTICES	100	
#define INF	1000000	/* ๋ฌดํ•œ๋Œ€ (์—ฐ๊ฒฐ์ด ์—†๋Š” ๊ฒฝ์šฐ) */

typedef struct GraphType {
	int n;	// ์ •์ ์˜ ๊ฐœ์ˆ˜
	int weight[MAX_VERTICES][MAX_VERTICES];
} GraphType;

int distance[MAX_VERTICES];/* ์‹œ์ž‘์ •์ ์œผ๋กœ๋ถ€ํ„ฐ์˜ ์ตœ๋‹จ๊ฒฝ๋กœ ๊ฑฐ๋ฆฌ */
int found[MAX_VERTICES];		/* ๋ฐฉ๋ฌธํ•œ ์ •์  ํ‘œ์‹œ */

int choose(int distance[], int n, int found[])
{
	int i, min, minpos;
	min = INT_MAX;
	minpos = -1;
	for (i = 0; i<n; i++)
		if (distance[i]< min && !found[i]) {
			min = distance[i];
			minpos = i;
		}
	return minpos;
}

void shortest_path(GraphType* g, int start)
{
	int i, u, w;
	for (i = 0; i<g->n; i++) /* ์ดˆ๊ธฐํ™” */
	{
		distance[i] = g->weight[start][i];
		found[i] = FALSE;
	}
	found[start] = TRUE;    /* ์‹œ์ž‘ ์ •์  ๋ฐฉ๋ฌธ ํ‘œ์‹œ */
	distance[start] = 0;
	for (i = 0; i<g->n-1; i++) {
		print_status(g);
		u = choose(distance, g->n, found);
		found[u] = TRUE;
		for (w = 0; w<g->n; w++)
			if (!found[w])
				if (distance[u] + g->weight[u][w]<distance[w])
					distance[w] = distance[u] + g->weight[u][w];
	}
}

int main(void)
{
	GraphType g = { 7,
	{{ 0,  7,  INF, INF,   3,  10, INF },
	{ 7,  0,    4,  10,   2,   6, INF },
	{ INF,  4,    0,   2, INF, INF, INF },
	{ INF, 10,    2,   0,  11,   9,   4 },
	{ 3,  2,  INF,  11,   0, INF,   5 },
	{ 10,  6,  INF,   9, INF,   0, INF },
	{ INF, INF, INF,   4,   5, INF,   0 } }
	};
	shortest_path(&g, 0);
	return 0;
}

์‹คํ–‰ ๊ฒฐ๊ณผ

C++ Code