java 二维变长数组_Java:存储可变大小的二维数组

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  > MazeList;

public void PrintList() {

for(int i= 0;i

for(int j = 0;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  >();

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());//if this line is empty

}else{

String[] line = temp.trim().split(" "); //get one line and split it

int j = 0;

MazeList.add(new Vector()); //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两个数 ,分别表示下一节点和对应的权值,可以用来算最优路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值