With one copy of each resource, a deadlock is exactly a cycle in the wait-for graph: an arrow a b means process a waits for a resource that process b holds.
What to build
Decide whether the wait-for graph has a cycle, and name the processes that are on one.
Requirements
- The graph has
nprocesses numbered from 0 andearrowsa b(a waits for b). Compute which processes can reach themselves by following one or more arrows. - If none can, print
deadlock: no. Otherwise printdeadlock: yesand then a second linein a cycle:with those processes in increasing order, such asin a cycle: P0 P2.
Input
The first line has n (1 ≤ n ≤ 10) and e (0 ≤ e ≤ 30). Then e lines, each with two numbers a b (0 to n−1). A process may wait for itself.
Output
deadlock: no, or deadlock: yes followed by the in a cycle: line.
Constraints
The same arrow may be listed twice.
Example
Input:
4 3
0 1
1 2
3 2
Output:
deadlock: no
Why it works
A process that can reach itself waits, directly or through others, for something it holds the key to, so it can never go on. Processes that only wait for a deadlocked process are stuck too, but they are not part of the cycle; the program names the cycle members only.
Examples
4 3 0 1 1 2 3 2
deadlock: no
3 3 0 1 1 2 2 0
deadlock: yes in a cycle: P0 P1 P2
Hints
Hint 1
Use an n by n matrix reach[i][j], set to 1 for every edge a to b.
Hint 2
Warshall: for k, then i, then j, set reach[i][j] to 1 if reach[i][k] and reach[k][j] are both 1.
Hint 3
Process i is in a cycle when reach[i][i] is 1 after that. If none is, print deadlock: no.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n, e, a, b, reach[10][10] = {{0}};
scanf("%d %d", &n, &e);
for (int i = 0; i < e; i++) {
scanf("%d %d", &a, &b);
reach[a][b] = 1;
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (reach[i][k] && reach[k][j]) reach[i][j] = 1;
int any = 0;
for (int i = 0; i < n; i++)
if (reach[i][i]) any = 1;
if (!any) {
printf("deadlock: no\n");
return 0;
}
printf("deadlock: yes\nin a cycle:");
for (int i = 0; i < n; i++)
if (reach[i][i]) printf(" P%d", i);
printf("\n");
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step