def is_safe_state(available, max_need, allocation):
n = len(max_need) # number of processes
m = len(available) # number of resource types
need = [[max_need[i][j] - allocation[i][j] for j in range(m)] for i in range(n)]
finish = [False] * n
work = available[:]
while True:
allocated_in_this_round = False
for i in range(n):
if not finish[i] and all(need[i][j] <= work[j] for j in range(m)):
for j in range(m):
work[j] += allocation[i][j]
finish[i] = True
allocated_in_this_round = True
if not allocated_in_this_round:
break
return all(finish)
# Example data
available = [3, 3, 2]
max_need = [
[7, 5, 3],
[3, 2, 2],
[9, 0, 2],
[2, 2, 2],
[4, 3, 3]
]
allocation = [
[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]
]
print("Is the system in a safe state?", is_safe_state(available, max_need, allocation))