Java 读取简单的数字阵列,比如
2
12 33 5
5
12 33 5
5
5
1 23 5
5
88 9
55 77
98
1 23 5
5
88 9
55 77
98
0
红色的是输入,黑色的为输出,各个数字之间用空格隔开,开头单独一行表示二维数组的行数,最后的0,表示结束。这个可以用来建立邻接表等
比如输入 :
3
1 2
2
0
表示结点 0 ,1 ,2之间的关系,0可以到1,2
1可以到2
2可以到0
import java.util.*;
class Maze {
private Vector < Vector < Integer > > MazeList;
public void PrintList() {
for(int i= 0;i<MazeList.size();i++){
for(int j = 0;j<MazeList.get(i).size();j++){
System.out.print(MazeList.get(i).get(j)+" ");
}
System.out.println(" ");
}
}
void run() throws Exception {
Scanner input = new Scanner(System.in);
String temp = input.nextLine();
String[] lines = temp.trim().split(" ");
while(lines.length==1){ //take the number of lines
MazeList = new Vector < Vector < Integer > >();
int TC = Integer.parseInt(lines[0]);
if( TC == 0 ) break;
int i = 0;
while(TC-- >0){
temp = input.nextLine();
if(temp.equals("")){
MazeList.add(new Vector<Integer>());//if this line is empty
}else{
String[] line = temp.trim().split(" "); //get one line and split it
int j = 0;
MazeList.add(new Vector<Integer>()); //add new line and add members
int num = line.length;
while(num-- >0){
MazeList.get(i).add(new Integer(Integer.parseInt(line[j])));
j++;
}
i++;
}
}
this.PrintList();
temp = input.nextLine();
lines = temp.trim().split(" ");
}
input.close();
}
public static void main(String[] args) throws Exception {
Maze maze = new Maze();
maze.run();
}
}
利用这个存储方式,还可以用来判断一些其他功能,比如判断A点到B点是否有路径可以到,或者将
private Vector < Vector < Integer > > MazeList;
改为
private Vector < Vector < IntegerPair > > MazeList;
自己写一下IntegerPair,包含first和second两个数 ,分别表示下一节点和对应的权值,可以用来算最优路径