Write a program to simulate a simple deadlock detection algorithm using the resource allocation graph.

Below is the C program to simulate a simple deadlock detection algorithm using the resource allocation graph.

	#include <stdio.h>
	#include <stdbool.h>

	#define MAX 10

	int alloc[MAX][MAX], max[MAX][MAX], avail[MAX];
	int need[MAX][MAX], n, m;

	void inputData() {
	    printf("Enter the number of processes: ");
	    scanf("%d", &n);
	    printf("Enter the number of resources: ");
	    scanf("%d", &m);
	    
	    printf("\nEnter the Allocation matrix:\n");
	    for (int i = 0; i < n; i++) {
	        for (int j = 0; j < m; j++) {
	            scanf("%d", &alloc[i][j]);
	        }
	    }

	    printf("\nEnter the Max matrix:\n");
	    for (int i = 0; i < n; i++) {
	        for (int j = 0; j < m; j++) {
	            scanf("%d", &max[i][j]);
	        }
	    }

	    printf("\nEnter the Available matrix:\n");
	    for (int i = 0; i < m; i++) {
	        scanf("%d", &avail[i]);
	    }
	}

	void calculateNeed() {
	    for (int i = 0; i < n; i++) {
	        for (int j = 0; j < m; j++) {
	            need[i][j] = max[i][j] - alloc[i][j];
	        }
	    }
	}

	bool isSafe() {
	    int work[m];
	    bool finish[n];
	    for (int i = 0; i < m; i++) {
	        work[i] = avail[i];
	    }
	    for (int i = 0; i < n; i++) {
	        finish[i] = false;
	    }

	    while (true) {
	        bool found = false;
	        for (int i = 0; i < n; i++) {
	            if (!finish[i]) {
	                int j;
	                for (j = 0; j < m; j++) {
	                    if (need[i][j] > work[j]) {
	                        break;
	                    }
	                }
	                if (j == m) {
	                    for (int k = 0; k < m; k++) {
	                        work[k] += alloc[i][k];
	                    }
	                    finish[i] = true;
	                    found = true;
	                }
	            }
	        }
	        if (!found) {
	            break;
	        }
	    }

	    for (int i = 0; i < n; i++) {
	        if (!finish[i]) {
	            return false;
	        }
	    }
	    return true;
	}

	int main() {
	    inputData();
	    calculateNeed();
	    if (isSafe()) {
	        printf("System is in a safe state.\n");
	    } else {
	        printf("System is in a deadlock state.\n");
	    }
	    return 0;
	}