Latin矩阵算法的Java实现

今天遇到一道算法题目,要求写出四阶拉丁矩阵中第一行为1,2,3,4的情形的其余三行的数,由于数目比较多,直接归纳写容易重复或者是遗忘,所以搞个程序输出就比较容易了。这个程序是我在网上找的例子后来又小改了下,贴出来备忘,呵呵 :)

package com.test;
public class Latin {
private final int n;
private int[][] m;
private int count = 0;

public Latin(int n) {
this.n = n;
m = new int[n][n];
fill(0);
}

public boolean check(int i, int j, int a) {
for(int col=0; col<j; col++)
if(m[i][col] == a) return false;
for(int row=0; row<i; row++)
if(m[row][j] == a) return false;
return true;
}

public void fill(int i) {
int row = i/n;
int col = i%n;
for(int a=1; a<=n; a++) {
if(check(row, col, a)) {
m[row][col] = a;
if(i == n*n-1) {
count++;
System.out.println(count);
for(int[] line : m) {
for(int x : line)
System.out.print(x);
System.out.println();
}
System.out.println("********");
}
else fill(i+1);
}
}
}

public static void main(String[] args) {
new Latin(4);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值