拉丁方阵-JAVA

该博客介绍了如何用JAVA编程语言来构造和打印n阶的拉丁方阵,拉丁方阵是一种特殊的矩阵,其中每一行和每一列都包含恰好n种不同的元素且每个元素仅出现一次。文章通过循环列表的方法来移动头节点,实现每个元素错开输出,从而完成拉丁方阵的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LatinSquare拉丁方阵JAVA解

问题介绍

传送门
n阶方阵中,恰有 n 种不同的元素,每一种不同的元素在同一行或同一列里只出现一次。

应用循环列表,不断移动头节点位置构造方阵的行(使每个元素错开输出),移动n-1次。
循环列表实现:(此处仅实现初始化)

public class CircleList {
    public Node headNode;
    public int listLength;

    public CircleList(int length) {
        Node head = new Node();
        Node tempP = head;
        Node tempQ = head;
        int count = 1;
        while (count <= length) {
            tempQ = new Node();
            tempQ.data = count++;
            tempQ.pre = tempP;
            tempQ.next = tempP.next;
            tempP.next = tempQ;
            tempP = tempQ;
            listLength++;
        }
        tempQ.next = head.next;
        head.next.pre = tempQ;
        headNode = tempQ.next;
    }

    public Node getHeadNode() {
        System.out.println(headNode.data);
        return headNode;
    }

    public void printList() {
        Node curNode = headNode;
        int count = 1;
        while (this.listLength >= count) {
            System.out.println(curNode.data);
            curNode = curNode.next;
            count++;
        }
    }
}
public class Node {
        int data;
        Node pre;
        Node next;

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

测试:

public class LatinSquare {

    public static void main(String[] args) {
        while (true){
            System.out.println("请输入矩阵次方");
            Scanner sc = new Scanner(System.in);
            if (sc.hasNextLine()) {
                String x = sc.nextLine();
                System.out.println(x);
                CircleList list = new CircleList(Integer.valueOf(x));
                int count = 1;
                while (count <= Integer.valueOf(x)){
                    System.out.println("方阵第"+count+"行:");
                    list.printList();
                    //移动头节点
                    list.headNode = list.headNode.getNext();
                    count++;
                }
                list.headNode = null;
                continue;
            } else {
                System.out.println("输入错误,请重新输入");
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值