Java 以字母为索引的邻接矩阵
嗨,我正在寻找一种实现邻接矩阵的方法,在这里我可以使用字母作为索引。。。像hashmap之类的东西 我目前使用的是一个简单的2D数组,我已经将字母a-Z转换为索引0-25(我可以在之后再转换回来,但这似乎是不必要的编码),这样:Java 以字母为索引的邻接矩阵,java,matrix,adjacency-matrix,digraphs,Java,Matrix,Adjacency Matrix,Digraphs,嗨,我正在寻找一种实现邻接矩阵的方法,在这里我可以使用字母作为索引。。。像hashmap之类的东西 我目前使用的是一个简单的2D数组,我已经将字母a-Z转换为索引0-25(我可以在之后再转换回来,但这似乎是不必要的编码),这样: matrix[initial][final] = 1; 其中: Index 0 1 2 3 0 0 1 1 0 1 1 0 0 0 2 0 1 0 0 3 0
matrix[initial][final] = 1;
其中:
Index 0 1 2 3
0 0 1 1 0
1 1 0 0 0
2 0 1 0 0
3 0 1 1 0
我希望能够使用A、B、C、D而不是0、1、2、3直接实现这一点
例如,如果我想添加一个条目:
matrix['A']['B'] = 1
(请注意,这应该在jdk 8上运行)
干杯试试这段代码可能会有帮助。
其思想是,数据存储在2D数组中,但为了访问元素,需要在其中创建特殊方法。
import java.util.HashMap;
import java.util.Map;
public class Mat {
int arr[][];
Map<String,Integer> hm;
int counter=0;
public static void main(String[] args)
{
Mat m = new Mat();
//create elements
m.addElement("a", "b", 2);
m.addElement("b", "a", 3);
m.addElement("c", "b", 33);
//get a particular element
System.out.println("[c,b]="+m.getElement("c", "b"));
//iterate through 2Dmatrix
for(int i=0;i<m.arr.length;i++)
for(int j=0; j<m.arr[i].length;j++)
{
System.out.println("["+m.getArr(i, j)[0]+","+m.getArr(i, j)[1]+"]="+m.arr[i][j]+" ("+m.getElement(m.getArr(i, j)[0], m.getArr(i, j)[1])+")");
}
}
//initialize here what ever letters are used, can be also numbers but in string format
Mat()
{
hm = new HashMap<String,Integer>();;
hm.put("a",counter++);
hm.put("b",counter++);
hm.put("c",counter++);
arr = new int[hm.size()][hm.size()];
}
public int getElement(String e1, String e2)
{
int i=hm.get(e1);
int j=hm.get(e2);
return arr[i][j];
}
public void addElement(String e1,String e2, int value)
{
int i=hm.get(e1);
int j=hm.get(e2);
arr[i][j] = value;
}
public String [] getArr(int i, int j)
{
String s[] = new String[2];
for(String str: hm.keySet())
{
if(hm.get(str) == i)
{
s[0] = str;
};
if(hm.get(str) == j)
{
s[1] = str;
};
}
return s;
}
}
[c,b]=33
//same values obtaining with two methods either directly form array
// or using a special one
[a,a]=0 (0)
[a,b]=2 (2)
[a,c]=0 (0)
[b,a]=3 (3)
[b,b]=0 (0)
[b,c]=0 (0)
[c,a]=0 (0)
[c,b]=33 (33)
[c,c]=0 (0)