# 图的遍历（dfs + bfs） + 最小生成树（prime） 模板

[提交][状态]

## 样例输入

4
0 1 0 1
1 0 0 0
0 0 0 1
1 0 1 0

## 样例输出

0 1 3 2 

# include <stdio.h>
# include <string.h>

int a[51][51], book[51];

int n;

void dfs(int cur)
{
printf("%d ", cur);

if (cur == n)
return;

int k;
for (k = 0; k < n; k ++)
{
if (a[cur][k] == 1 && book[k] == 0)
{
book[k] = 1;
dfs(k);
}
}
return;
}
int main(void)
{
int i ,j;
while (~ scanf("%d", &n))
{
for (i = 0; i < n; i ++)
for (j = 0; j < n; j ++)
scanf("%d", &a[i][j]);
memset(book, 0, sizeof(book));
book[0] = 1;
dfs(0);
}
return 0;
}

[提交][状态]

## 样例输入

4
0 0 0 1
0 0 1 1
0 1 0 1
1 1 1 0

## 样例输出

0 3 1 2 

# include <stdio.h>
# include <string.h>

int a[51][51], qwe[1501], book[51];

int main(void)
{
int t, c, i, j;
while (~ scanf("%d", &t))
{
memset(book, 0, sizeof(book));
memset(qwe, 0, sizeof(qwe));
for (i = 0; i < t; i ++)
for (j = 0; j < t; j ++)
scanf("%d", &a[i][j]);

int head = 0, tail = 0;
qwe[tail] = 0;
tail ++;
book[0] = 1;
int cur, k;
while (head < tail && tail < t)
{
for (k = 0; k < t; k ++)
{
if (a[cur][k] == 1 && book[k] == 0)
{
qwe[tail] = k;
tail ++;
book[k] = 1;
}
if (tail >= t)
break;
}
}
for (i = 0; i < tail; i ++)
printf("%d ", qwe[i]);
printf("\n");
}
return 0;
}

[提交][状态]

## 样例输入

4
0 2 4 0
2 0 3 5
4 3 0 1
0 5 1 0

## 样例输出

6

# include <stdio.h>
# include <string.h>

int main(void)
{
int t, a[51][51], book[51], dis[51];
while (~ scanf("%d", &t))
{
memset(book, 0, sizeof(book));
int i, j;
for (i = 1; i <= t; i ++)
for (j = 1; j <= t; j ++)
{
scanf("%d", &a[i][j]);
if(i != j && a[i][j] == 0)
a[i][j] = 99999999;
}
int count = 0, sum = 0;
book[1] = 1;
count ++;
int min;
for (i = 1; i <= t; i ++)
dis[i] = a[1][i];

while (count < t)
{
min = 99999999;
for (i = 1; i <= t; i ++)
{
if (book[i] == 0 && dis[i] < min)
{
min = dis[i];
j = i;
}
}
book[j] = 1;
count ++;
sum += dis[j];
for (int k = 1; k <= t; k ++)
{
if (book[k] == 0 && dis[k] > a[j][k])
dis[k] = a[j][k];
}
}
printf("%d\n", sum);
}
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120