Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列和行为字符串的邻接矩阵_Java_Arrays_String_Graph - Fatal编程技术网

Java 列和行为字符串的邻接矩阵

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

需要创建一个邻接矩阵,其中行和列是字符串,矩阵中存储的值是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>() {{
        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"