Graph

数据结构及算法 | 2016-08-09 20:21:38 | 阅读 1967 次 | 评论(0)
public class Node {
	
		private Object value;

		public Node(Object value) {
			this.value = value;
		}

		public String toString() {
			return value == null ? "" : value.toString();
		}

	}



/***************************************************/



public class Border {

	public Node fnode;
	public Node lnode;

	public Border(Node fnode, Node lnode) {
		this.fnode = fnode;
		this.lnode = lnode;
	}
}



/**************************************************/


public class Graph {

	private static final int CONN = 1;
	private Node[] nodes;

	private int[][] matrix;

	public Graph(Node[] nodes, Border[] borders) {
		this.nodes = nodes;
		this.matrix = new int[nodes.length][nodes.length];
		connect(borders);
	}

	public void connect(Border[] borders) {
		Node fnode;
		Node lnode;
		for (int i = 0; i < borders.length; i++) {
			fnode = borders[i].fnode;
			lnode = borders[i].lnode;
			int findex = findindex(fnode);
			int lindex = findindex(lnode);
			if (findex >= 0 && findex < nodes.length && lindex >= 0
					&& lindex < nodes.length) {
				matrix[findex][lindex] = CONN;
				matrix[lindex][findex] = CONN;

			}
		}
	}

	public int findindex(Node node) {
		for (int i = 0; i < nodes.length; i++) {
			if (node.equals(nodes[i])) {
				return i;
			}
		}
		return -1;
	}

	public String printmatrix() {
		StringBuffer a = new StringBuffer();
		a.append("Gromax: \n");
		for (int i = 0; i < nodes.length; i++) {
			a.append(nodes[i] + "");
			for (int k = 0; k < nodes.length; k++) {
				a.append(matrix[i][k] + " ");
			}
			a.append("\n");
		}

		return a.toString();
	}

}


/*********************************************/


public class MainActivity extends Activity {

	Node node1, node2, node3, node4, node5;
	Border border1, border2, border3, border4, border5;
	TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.textView2);
		node1 = new Node("A");
		node2 = new Node("B");
		node3 = new Node("C");
		node4 = new Node("D");
		node5 = new Node("E");

		border1 = new Border(node1, node3);
		border2 = new Border(node1, node4);
		border3 = new Border(node2, node3);
		border4 = new Border(node2, node5);
		border5 = new Border(node4, node5);

		Node[] nodes = new Node[] { node1, node2, node3, node4, node5 };
		Border[] borders = new Border[] { border1, border2, border3, border4,
				border5 };
		Graph g = new Graph(nodes, borders);
		tv = (TextView) findViewById(R.id.textView2);

		tv.setText(g.printmatrix());

	}


}
文章评论,共0条
游客请输入验证码
浏览172233次
最新评论
  • zhouwenyuan:博主可以开发房产APP吗?
  • qunxingw:结合附件,在分表A或B...实验一下宏就理解了
  • qunxingw:这仅是小范围的一种思路,此题是指数级的数据。