import numpy as np

# 参数设置
p = 0.85  # 继续浏览当前网页的概率
a = np.array([[1, 0, 0, 0],
              [0, 0, 0, 1],
              [0, 0, 0, 1],
              [0, 1, 0, 0]], dtype=float)

length = a.shape[1]  # 网页数量
b = np.transpose(a).copy()  # 转置并复制以避免修改原始矩阵
m = np.zeros((a.shape), dtype=float)

# 构造转移矩阵（修正 Dead Ends）
for j in range(b.shape[0]):
    if b[j].sum() == 0:  # 处理 Dead Ends
        b[j] = np.ones(length) / length  # 修正为均匀分布
    for i in range(b.shape[1]):
        m[i][j] = b[j][i] / b[j].sum()  # 使用修正后的 b[j][i]

# 初始化 PageRank 值
v = np.ones(length).reshape(-1, 1) / length
ee = np.ones(length).reshape(-1, 1) / length

# 迭代计算 PageRank 值
for _ in range(100):
    v = p * np.dot(m, v) + (1 - p) * ee

print("修正后的 PageRank 值：")
print(v)