将一个稀疏矩阵从一个二维数组转变成只包含非零结点的多链表

代码:


package Matriix;

import java.util.Scanner;

public class Demo1 {

	//将一个稀疏矩阵从一个二维数组转变成只包含非零结点的多链表
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		int V = scan.nextInt();
		int E = scan.nextInt();
		boolean[][] adj = new boolean[V][V];
		Node ad[] = new Node[E];
		
		for(int i=0;i<V;i++){
			for(int j=0;j<V;j++){
				adj[i][j] = false;
			}
		}
		//初始化一个稀疏矩阵
		for(int i=0;i<E;i++){
			String input = scan.next();
			int x = Integer.parseInt(input.substring(1, 2));
			int y = Integer.parseInt(input.substring(3, 4));
			adj[x][y] = true;
			adj[y][x] = true;
		}//i,j即为点坐标
		//转化
		int count = 0;
		for(int i=0;i<V;i++){
			for(int j=0;j<count;j++){
				if(adj[i][j]){//(i,j)
					ad[i] = new Node(j,ad[i]);
					ad[j] = new Node(i,ad[j]);
				}
			}
			count++;
		}
		//输出
		for(int i=0;i<V;i++){
			for(Node temp=ad[i];temp!=null;temp=temp.next){
				System.out.print(temp.val+" ");
			}
			System.out.println();
		}
	}

	static class Node{
		int val;
		Node next;
		public Node(int val,Node next){
			this.val = val;
			this.next = next;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值