如何正确接受平方加权邻接矩阵

How do you properly accept a square weighted adjacency matrix?

本文关键字:加权 邻接矩阵 方加权 何正确      更新时间:2023-10-16

我正在尝试重新创建Kruskal和Prim的算法。为此,我需要输入一个加权邻接矩阵。

加权邻接矩阵的示例输入为:

0   0   355 0   695 0   0   0
0   0   74  0   0   348 0   0
355 74  0   262 0   269 0   0
0   0   262 0   0   242 0   0
695 0   0   0   0   151 0   0
0   348 269 242 151 0   83  306
0   0   0   0   0   83  0   230
0   0   0   0   0   306 230 0

这些数字已经过少量编辑,以提供更清晰的信息。每个数字之间应该有一个空格。

至于接受这些值并记录它们,我可以使用以下代码接受其中的一行:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
        string temp;
        string buf;
        vector<string> matrix;
        cout << "Matrix: ";
        getline(cin, temp);
        stringstream ss(temp);
        while(ss >> buf)
        {
                matrix.push_back(buf);
        }
        for(int i = 0; i < matrix.size(); i++)
        {
                cout << matrix[i] << " ";
        }
        cout << endl;
        return 0;
}

示例输出:

Matrix: 0 0 355 0 695 0 0 0
0 0 355 0 695 0 0 0

关于我的问题,我怎样才能要求正确数量的矩阵行并记录所有矩阵行?

在示例中,我将如何要求另外 7 行矩阵值(在接受值之前不需要 cout/cin 语句(?

让我们将

您已经拥有的内容提取到一个函数中:

std::vector<std::string> read_row(std::istream & is)
{
    string line;
    string number;
    vector<string> row;
    getline(is, line);
    stringstream ss(line);
    while(ss >> number)
    {
         row.push_back(number);
    }
    return row;
}

现在我们可以多次执行此操作

int main()
{
     std::vector<std::vector<std::string>> matrix;
     std::vector<std::string> first_row = read_row(std::cin);
     matrix.push_back(first_row);
   // We already have the first line, so loop from 1
     for (int i = 1; i < first_row.size(); ++i)
     {
          std::vector<std::string> next_row = read_line(std::cin);
          if (next_row.size() != first_row.size())
          {
               std::cout << "Row " << i << " does not match length";
               return 1;
          }
          matrix.push_back(next_row);
     }
     return 0;
 }

现在您可能想使用这些数字进行计算,因此您可以使用 intdouble 代替std::stringss >> number是格式化输入,因此它会为您将文本转换为数字。