|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
创建图的时候发生异常
for循环中j的数值非常大
图的邻接矩阵
源码:
#include <iostream>
using namespace std;
template<typename V,typename E>
class adjMatrix {
private:
V* vertexs;
E** edges;
E noEdge;
//int verNum, edgeNum;
//bool* visited;
void dfs(int start)const;
public:
adjMatrix(int size, E noEdgeFlag) {
verNum = size;
edgeNum = 0;
noEdge = noEdgeFlag;
vertexs = new V[verNum];
edges = new E * [verNum];
for (int i = 0; i < verNum; i++) {
edges[i] = new E[verNum];
for (int j = 0; j < verNum; ++j)
edges[i][j] = noEdge;
}
visited = new bool[verNum];
TE = new mstEdge[verNum - 1];
}
~adjMatrix() {
delete[] vertexs;
for (int i = 0; i < verNum; i++)
delete[] edges[i];
delete[] edges;
delete[] visited;
delete[] TE;
}
void createGraph(const V V[], const E E[]);
void printGraph()const;
//bool searchEdge(int from, int to)const;
bool insertEdge(int from, int to, E w);
//bool removeEdge(int from, int to);
void dfsTraverse()const;
void bfsTraverse()const;
protected:
struct mstEdge {
int vex1, vex2;
E weight;
bool operator<(const mstEdge& e)const {
return weight < e.weight;
}
}*TE;
int verNum, edgeNum;
bool* visited;
};
template<typename V, typename E>
void adjMatrix<V, E>::dfs(int start)const {
int i;
cout << vertexs[start]<< ' ';
visited[start] = true;
for (i = 0; i < verNum; i++) {
if (edges[start][i] != noEdge && visited[i] == false)
dfs(i);
}
}
template<typename V, typename E>
bool adjMatrix<V, E>::insertEdge(int from, int to, E w) {
if (from<0 || from>verNum - 1 || to<0 || to>verNum - 1)
return false;
if (edges[from][to] == w)
return false;
if (edges[from][to] == noEdge)
++edgeNum;
edges[from][to] = w;
return true;
}
template<typename V, typename E>
void adjMatrix<V, E>::createGraph(const V Vv[], const E Ee[]) {
int i, j;
for (i = 0; i < verNum; i++)
vertexs[i] = Vv[i];
for (i = 0; i < verNum; i++) {
for (j = 0; i < verNum; j++)
if (Ee[i * verNum + j] > 0)
insertEdge(i, j, Ee[i * verNum + j]);
}
}
int main()
{
int a[3] = {1,2,3};
int b[9] = {0,1,1,0,0,1,0,1,0};
adjMatrix<int,int>matrix(3,0);
matrix.createGraph(a, b);
return 0;
} |
-
|