grcreatm.cpp

来自「经典c++程序的实现」· C++ 代码 · 共 75 行

CPP
75
字号
#include <stdio.h>
#include <iostream.h>
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>

#include "..\..\include\book.h"

#define LINELEN 80

#include "..\..\include\grmat.h"

char* getl(char* buffer, int n, FILE* fid) {
  char* ptr;
  ptr = fgets(buffer, n, fid);
  while ((ptr != NULL) && (buffer[0] == '#'))
    ptr = fgets(buffer, n, fid);
  return ptr;
}

// Create a graph from file
bool createGraph(Graph& G, FILE* fid) {
  char buffer[LINELEN+1]; // Line buffer for reading
  bool undirected;  // TRUE if graph is undirected, FALSE if directed
  int i;
  int v1, v2, dist;

  if (getl(buffer, LINELEN, fid) == NULL) // Unable to get number of vertices
{ cout << "Unable to read number of vertices\n";
    return FALSE;
}
  G.numVertex = atoi(buffer);
  if (getl(buffer, LINELEN, fid) == NULL) // Unable to get graph type
{ cout << "Unable to read graph type\n";
    return FALSE ;
}
  if (buffer[0] == 'U')
    undirected = TRUE;
  else if (buffer[0] == 'D')
    undirected = FALSE;
  else {
    cout << "Bad graph type: |" << buffer << "|\n";
    return FALSE;
  }

  // Create space
  G.Mark = new bool[G.n()];
  G.matrix = new int[G.n() * G.n()];
  for (i=0; i< G.n()*G.n(); i++) // Initialize matrix
    G.matrix[i] = -1;

  // Read in edges
  G.numEdge = 0;
  while (getl(buffer, LINELEN, fid) != NULL) {
    v1 = atoi(buffer);
    i = 0;
    while (isdigit(buffer[i])) i++;
    while (buffer[i] == ' ') i++;
    v2 = atoi(&buffer[i]);
    while (isdigit(buffer[i])) i++;
    if (buffer[i] == ' ') { // There is a distance
      while (buffer[i] == ' ') i++;
      dist = atoi(&buffer[i]);
    }
    else dist = 1;
    G.matrix[v1*G.n() + v2] = dist;
    G.numEdge++;
    if (undirected) { // Put in edge in other direction
      G.matrix[v2*G.n() + v1] = dist;
      G.numEdge++;
    }
  }
  return TRUE;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?