import torch


def build_sparse_adjacent_matrix(edges: list, n: int, device=None, dtype=torch.float, undirectional=True):
    """
    Return adjacency matrix
    :param edges: list of edges, for example (st, ed)
    :param n: number of vertices
    :param device:
    :param dtype:
    :param undirectional: make adjacency matrix un-directional
    :return: the sparse adjacent matrix
    """
    i = torch.tensor(list(zip(*edges)))
    v = torch.ones(i.shape[1], dtype=dtype)
    sparse = torch.sparse_coo_tensor(i, v, (n, n))
    if device is not None:
        sparse = sparse.to(device)
    a = sparse.to_dense()
    if undirectional:
        ud_a = ((a > 0) | (a.transpose(-2, -1) > 0)).to(dtype)
        a = ud_a
    return a