#include <iostream>
using namespace std;
int main() {
int numProcesses, numResources;
cout << "Enter the number of processes: ";
cin >> numProcesses;
cout << "Enter the number of resources: ";
cin >> numResources;
// Input matrices and arrays
int allocation[10][10], max[10][10], need[10][10], available[10];
bool finish[10] = {false}; // Keep track of finished processes
int safeSequence[10]; // To store the safe sequence
// Input Allocation matrix
cout << "Enter the Allocation matrix:" << endl;
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
cin >> allocation[i][j];
}
}
// Input Max matrix
cout << "Enter the Max matrix:" << endl;
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
cin >> max[i][j];
// Calculate the Need matrix on the fly
need[i][j] = max[i][j] - allocation[i][j];
}
}
// Input Available resources
cout << "Enter the Available resources:" << endl;
for (int i = 0; i < numResources; i++) {
cin >> available[i];
}
int count = 0; // Number of processes completed
bool foundDeadlock = false; // Flag for deadlock detection
while (count < numProcesses) {
bool found = false;
for (int i = 0; i < numProcesses; i++) {
if (!finish[i]) { // Process not finished
bool canProceed = true;
// Check if the process can proceed (if its need is <= available)
for (int j = 0; j < numResources; j++) {
if (need[i][j] > available[j]) {
canProceed = false;
break;
}
}
if (canProceed) {
// Add allocated resources back to available
for (int j = 0; j < numResources; j++) {
available[j] += allocation[i][j];
}
safeSequence[count++] = i;
finish[i] = true;
found = true;
break;
}
}
}
// If no process can proceed, then there's a deadlock
if (!found) {
cout << "The system is in a deadlock state." << endl;
foundDeadlock = true;
break;
}
}
// If no deadlock is detected, print the safe sequence
if (!foundDeadlock) {
cout << "The system is in a safe state. Safe sequence is: ";
for (int i = 0; i < numProcesses; i++) {
cout << "P" << safeSequence[i];
if (i < numProcesses - 1) {
cout << " -> ";
}
}
cout <<"\n No Deadlock Occurs"<< endl;
} else {
// Display which processes are involved in the deadlock
cout << "Deadlocked processes: ";
for (int i = 0; i < numProcesses; i++) {
if (!finish[i]) {
cout << "P" << i << " ";
}
}
cout << endl;
}
return 0;
}