当前位置: 代码迷 >> J2SE >> 算法,求一算法的代码
  详细解决方案

算法,求一算法的代码

热度:35   发布时间:2016-04-24 13:40:57.0
算法高手请进,求一算法的代码
一个3×3的二维数组,里面初始几个位置有1-9之间随机的一个数字,例如:

1   空   空
空   4   空
8   空   9

现在要求打印出1-9把这9格填满的所有方案

求代码

------解决方案--------------------
这个就是求几个数的全排列啊,不难吧

------解决方案--------------------
取{ 2, 3, 5, 6, 7 }所有的排列组合就可以了。

填充方案:

int a[] = { 2, 3, 5, 6, 7 };
int len = a.length;
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++) {
if (j == i)
continue;
for (int k = 0; k < len; k++) {
if (k == i || k == j)
continue;
for (int l = 0; l < len; l++) {
if (l == i || l == j || l == k)
continue;
for(int m=0;m <len;m++){
if(m==i || m==j || m==k || m==l)
continue;
System.out.println( "1, "+a[i] + ", " + a[j] + ", " + a[k] + ",4, "
+ a[l]+ ",8, "+a[m]+ ",9 ");
}
}
}
}

}
------解决方案--------------------
排列组合的问题,没事就写一个玩玩吧,关键是parade方法,从一个数组中抽出n个元素进行全排列

import java.io.*;
import java.util.Vector;

public class Game {
public static void main(String[] args) {
new Game().solve();

// test play
// new Game().play();

// test parade
// Game game = new Game();
// for (int i=1; i <game.size-1; i++) {
// System.out.println( "--------elements: " + (i+1) + "-------- ");
// game.printParadeResult(game.parade(game.all, i));
// }
}

int[] all = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] taken, remain;
int size = all.length;
int width = (int)Math.sqrt(size);

public void solve() {
taken = new int[] {1, 4, 8, 9};
remain = new int[] {2, 3, 5, 6, 7};
int[][] matrix = new int[width][width];
matrix[0][0] = taken[0];
matrix[1][1] = taken[1];
matrix[2][0] = taken[2];
matrix[2][2] = taken[3];

printMatrix(matrix);

int[][] result = parade(remain, remain.length);
printMatrixResult(matrix, result);
}


public void play() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
int n = 0;
while (true) {
System.out.print( "Input number of initial elements: ");
s = br.readLine();
try {
n = Integer.parseInt(s);
if (n <0 || n> all.length) {
throw new Exception( "please input a number between 0 and 9. ");
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println( "Input error, press enter key to try again or type [go] to exit. ");
s = br.readLine();
if (s != null && "go ".equals(s)) {
break;
}
continue;
}

int[][] matrix = init(n);
printMatrix(matrix);

int[][] result = parade(remain, remain.length);
printMatrixResult(matrix, result);
  相关解决方案