g****9 发帖数: 163 | 1 写了一个graph的class 但是下面第一种写法是错误的,我不是太明白,是因为
GNode node1 = null;GNode node2 = null吗?这时候node1跟node2并没有allocate
memory,所以就算后面if statement里面的node1 = new GNode(key1) 也只是在if这个
block里面有效的吧,在最后node1.connect(node2)里node1 是不是还是null呢 求指
点。第二个graph class 就可以work的。
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap();
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
if (!nodes.containsKey(key1)){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
if (!nodes.containsKey(key2){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
}
第二种写法 就work的,我只是添加了node1 = nodes.get(key1);跟node2 = nodes.get
(key2);
class Graph {
private HashMap nodes;
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap();
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
node1 = nodes.get(key1);
if (node1 == null){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
node2 = nodes.get(key2);
if (node2 == null){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
} | g****9 发帖数: 163 | | d****n 发帖数: 1637 | 3 用debug看看,
for (int j = 0; j < adjacencyMatrix[0].length; j++) ???
是不是应该
for (int j = 0; j < adjacencyMatrix[i].length; j++)
没有i?不懂你咋定义的,但是感觉上,你没进入inner loop啊,
把 GNode 定义拿来看看。
用vs debugge 运行,设置断点
node1 = nodes.get(key1);这一行, 你就差不多知道答案了 | g****9 发帖数: 163 | 4 GNode的定义是这个。adjacencyMatrix 是N*N的matrix,N是Node的个数。比如
int[][] adjacencyMatrix = {{1, 1, 0, 0, 1, 0},{1, 0, 0, 0, 1, 0},{0, 0, 0, 0
, 0, 0},{0, 0, 0, 0, 1, 1},{1, 1, 0, 1, 0, 0},{0, 0, 0, 1, 0, 0}}; 这个
matrix分别有6个node,每个node的value是1,2,3,4,5,6.定义的这个graph class我是
想用来验证关于graph的code的正确不,所以想简单化node 的value,让自动取i+1作为
node的value值。
class GNode {
private int val;
private boolean discovered;
private ArrayList adj;
public GNode (int x) {
val = x;
adj = new ArrayList();
}
public int getVal() {
return val;
}
public void setVal(int x) {
val = x;
}
public boolean isDiscovered(){
return discovered;
}
public void setDiscovered(boolean discovered){
this.discovered = discovered;
}
public ArrayList getAdj(){
return adj;
}
public void setAdj(ArrayList adj) {
this.adj = adj;
}
public void connect(GNode node) {
this.adj.add(node);
}
@Override
public String toString(){
return val + " ";
}
}
【在 d****n 的大作中提到】 : 用debug看看, : for (int j = 0; j < adjacencyMatrix[0].length; j++) ??? : 是不是应该 : for (int j = 0; j < adjacencyMatrix[i].length; j++) : 没有i?不懂你咋定义的,但是感觉上,你没进入inner loop啊, : 把 GNode 定义拿来看看。 : 用vs debugge 运行,设置断点 : node1 = nodes.get(key1);这一行, 你就差不多知道答案了
|
|