private void button7_Click(object sender, EventArgs e) { // 从 listView1 中读取 NFA 数据 List<string[]> nfaData = new List<string[]>(); foreach (ListViewItem item in listView1.Items) { string[] row = new string[3]; row[0] = item.SubItems[0].Text; // 起始状态 row[1] = item.SubItems[1].Text; // 接受符号 row[2] = item.SubItems[2].Text; // 到达状态 nfaData.Add(row); }

// 转换为 DFA 数据
List<string[]> dfaData = new List<string[]>();

// 将 NFA 转换为 DFA
List<string> states = new List<string>(); // 存储 DFA 状态
List<string[]> transitions = new List<string[]>(); // 存储 DFA 转换

// 初始化状态集合
List<string> initialStates = new List<string>();
initialStates.Add('0');
states.Add('0');
while (initialStates.Any())
{
    string[] row = new string[2];
    row[0] = string.Join(',', initialStates);
    row[1] = '';
    foreach (string state in initialStates)
    {
        // 查找该状态的所有转换
        foreach (string[] nfaRow in nfaData)
        {
            if (nfaRow[0] == state && !initialStates.Contains(nfaRow[2]))
            {
                initialStates.Add(nfaRow[2]);
            }
        }

        // 如果该状态是接受状态,则将接受符号添加到 DFA 状态中
        foreach (string[] nfaRow in nfaData)
        {
            if (nfaRow[0] == state && nfaRow[1] != '' && !row[1].Contains(nfaRow[1]))
            {
                row[1] += nfaRow[1];
            }
        }
    }
    initialStates.RemoveRange(0, 1);
    transitions.Add(row);

    // 添加新状态
    if (!states.Contains(row[0]))
    {
        states.Add(row[0]);
    }
}

// 处理转换
for (int i = 0; i < states.Count; i++)
{
    string[] row = transitions[i];
    string[] newState = new string[2];
    newState[0] = states[i];
    for (int j = 0; j < row[1].Length; j++)
    {
        char symbol = row[1][j];
        List<string> nextStateSet = new List<string>();
        foreach (string[] nfaRow in nfaData)
        {
            if (row[0].Split(',').Contains(nfaRow[0]) && nfaRow[1] == symbol.ToString())
            {
                if (!nextStateSet.Contains(nfaRow[2]))
                {
                    nextStateSet.Add(nfaRow[2]);
                }
            }
        }
        if (nextStateSet.Any())
        {
            string nextStates = string.Join(',', nextStateSet.OrderBy(s => s));
            newState[1] += symbol + ':' + nextStates + ';';
            if (!states.Contains(nextStates))
            {
                states.Add(nextStates);
            }
        }
    }
    dfaData.Add(newState);
}

// 将 DFA 数据显示在 listView2 中
listView2.Items.Clear();
foreach (string[] row in dfaData)
{
    ListViewItem item = new ListViewItem(row);
    listView2.Items.Add(item);
}

}

C# 实现 NFA 转 DFA 功能,无需调用或定义新函数

原文地址: https://www.cveoy.top/t/topic/nsJX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录