---
title: "Graph 图－邻接矩阵法"
author: "shenyu"
date: "2008-04-16T22:56:47Z"
tags: ["数据结构", "算法"]
slug: "graph"
draft: false
lastmod: "2008-04-16T22:56:47Z"
id: 183543
url: "https://shenyu.iteye.com/blog/183543"
---

用邻接矩阵法表示的双向图（改单向容易，只要修改connect,disconect方法）。

此处只是表示数据结构，没有相关算法。

其中Vertex是辅助类表示顶点，其中包含一个boolean变量isVisited表示是否遍历过。

Graph表示图，实际存储顶点，以及顶点之间的关系（用二维数组表示）

另一个实现请请[参见](183563)

```
class Vertex {
	private Object value;
	private boolean isVisited;
	Vertex(Object value) {
		this.value = value;
	}

	void visit() { isVisited = true; }
	boolean isVisited() { return isVisited; }
}

class Gragh {
	private Vertex[] vertexs;
	private int[][] adjMat;
	private int pos = -1;

	Gragh(int size) {
		vertexs = new Vertex[size];
		adjMat = new int[size][size];
	}

	void add(Object value) {
		assert pos < vertexs.length;
		vertexs[++pos] = new Vertex(value);
	}

	void connect(int from, int to) {
		adjMat[from][to] = 1;
		adjMat[to][from] = 1;
	}

	void disConnect(int from, int to) {
		adjMat[from][to] = 0;
		adjMat[to][from] = 0;
	}
}
```