Sprno:9223
8 IMPLEMENT DEADLOCK DETECTION ALGORITHM
PROGRAM:
             #include <stdio.h>
             #include <stdbool.h>
             int main()
             {
                 int n, m, i, j, count = 0;
                 printf("Enter total number of processes: ");
                 scanf("%d", &n);
                 printf("Enter total number of resources: ");
                 scanf("%d", &m);
                 int allocation[n][m], maximum[n][m], available[m], need[n][m];
                 int finished[n];
                 printf("Enter Allocation Matrix (allocated resources for each process):\n");
                 for (i = 0; i < n; i++)
                   for (j = 0; j < m; j++)
                      scanf("%d", &allocation[i][j]);
                 printf("Enter Maximum Matrix (maximum resources required by each
process):\n");
                 for (i = 0; i < n; i++)
                   for (j = 0; j < m; j++)
                      scanf("%d", &maximum[i][j]);
                 printf("Enter Available Resources:\n");
                 for (i = 0; i < m; i++)
                                                         Sprno:9223
    scanf("%d", &available[i]);
// Calculate need matrix
for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        need[i][j] = maximum[i][j] - allocation[i][j];
    }
}
// Initialize all processes as unfinished
for (i = 0; i < n; i++)
    finished[i] = 0;
// Deadlock detection loop
bool progress;
do {
    progress = false;
    for (i = 0; i < n; i++)
    {
        if (!finished[i])
        {
            bool can_finish = true;
            for (j = 0; j < m; j++)
            {
                if (need[i][j] > available[j])
                {
                    can_finish = false;
                    break;
                                                                   Sprno:9223
                }
            }
            if (can_finish)
            {
                for (j = 0; j < m; j++)
                {
                    available[j] += allocation[i][j];
                }
                finished[i] = 1;
                progress = true;
                count++;
            }
        }
    }
} while (progress);
if (count == n)
{
    printf("No deadlock detected, all processes can finish.\n");
}
else
{
    printf("Deadlock detected among processes:\n");
    for (i = 0; i < n; i++)
    {
        if (!finished[i])
            printf("Process P%d\n", i);
    }
}
                                                                         Sprno:9223
              return 0;
          }
OUTPUT:
    Enter total number of processes: 4
    Enter total number of resources: 3
    Enter Allocation Matrix (allocated resources for each process):
    010
    200
    303
    211
    Enter Maximum Matrix (maximum resources required by each process):
    753
    322
    903
    422
    Enter Available Resources:
    332
    No deadlock detected, all processes can finish.