Program:
#include <iostream> using namespace std; int n, m; void display(int mat[5][3]) { for (int i = 0; i < n; i++) { cout << endl; for (int j = 0; j < m; j++) { cout << mat[i][j] << " "; } } } int main() { cout << "\n\n Enter number of process:"; cin >> n; cout << "\n\n Enter number of resources:"; cin >> m; int alloc[n][3], need[n][3], max[n][3]; int available[m]; cout << "\n\n Enter Allocation Matrix:"; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> alloc[i][j]; } } cout << "\n\n Enter Max Matrix:"; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> max[i][j]; } } cout << "\n\n Enter available Array:"; for (int i = 0; i < m; i++) { cin >> available[i]; } cout << "\n\n Displaying Allocation Matrix:"; display(alloc); cout << "\n\n Displaying Max Matrix:"; display(max); cout << "\n\n Displaying Available Array:"; for (int i = 0; i < m; i++) { cout << available[i] << " "; } // Step 1: Creating Need matix for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { need[i][j] = max[i][j] - alloc[i][j]; } } cout << "\n\n Displaying Need Matrix:"; display(need); // Step 2: Creating Flag variable to keep track of which process complete int flag[n]; for (int i = 0; i < n; i++) { flag[i] = 0; } // Step 3: Allocating Resources if available is greater than need int safe_seq[n], ct = 0; int i, j, k, f; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { f = 0; if (flag[i] == 1) { continue; } for (j = 0; j < m; j++) { if (available[j] < need[i][j]) { f = 0; break; } else { f = 1; } } if (f == 1) { flag[i] = 1; break; } } if (i == n) { continue; } if (flag[i] == 1) { safe_seq[ct] = i; ct++; for (j = 0; j < m; j++) { available[j] += alloc[i][j]; } } } f = 0; // Checking if Safe Sequence is present or not for (int i = 0; i < n; i++) { if (flag[i] == 0) { cout << "\n\n Safe Sequence Not Present!"; f = 1; break; } } // Printing Safe Sequence if (f == 0) { cout << "\n\n Safe Seqence:"; for (int i = 0; i < n; i++) { cout << "P" << safe_seq[i] + 1 << ","; } } return 0; }
Output: