Java 列和行为字符串的邻接矩阵
需要创建一个邻接矩阵,其中行和列是字符串,矩阵中存储的值是0或1,表示是否存在从源到目标的连接 例如:如果a->b、b->c是连接,则矩阵应如下所示:Java 列和行为字符串的邻接矩阵,java,arrays,string,graph,Java,Arrays,String,Graph,需要创建一个邻接矩阵,其中行和列是字符串,矩阵中存储的值是0或1,表示是否存在从源到目标的连接 例如:如果a->b、b->c是连接,则矩阵应如下所示: a b c a 0 1 0 B001 C000 正在寻找一个解决方案来实现这个类似矩阵[a][b]=1; 当我们试图使用字符串而不是整数位置访问矩阵时,会引发错误。您可以尝试对字符串进行编码。例如: Map<String, Integer> codec = new HashMap<String, Integer&g
a b c
a 0 1 0
B001
C000
正在寻找一个解决方案来实现这个类似矩阵[a][b]=1;
当我们试图使用字符串而不是整数位置访问矩阵时,会引发错误。您可以尝试对字符串进行编码。例如:
Map<String, Integer> codec = new HashMap<String, Integer>() {{
put("a", 0);
put("b", 1);
put("c", 2);
}};
int adjMatrix[][] = new int[][]{
{0, 1, 0},
{0, 0, 1},
{0, 0, 0}
};
System.out.println(adjMatrix[codec.get("a")][codec.get("b")]); //prints "1"
Map<String, Map<String, Integer>> adjMatrix = new HashMap<>();
Map<String, Integer> aRow = new HashMap<>();
aRow.put("a", 0);
aRow.put("b", 1);
aRow.put("c", 0);
Map<String, Integer> bRow = new HashMap<>();
bRow.put("a", 0);
bRow.put("b", 0);
bRow.put("c", 1);
Map<String, Integer> cRow = new HashMap<>();
cRow.put("a", 0);
cRow.put("b", 0);
cRow.put("c", 0);
adjMatrix.put("a", aRow);
adjMatrix.put("b", bRow);
adjMatrix.put("c", cRow);
System.out.println(adjMatrix.get("a").get("b")); // prints "1"