# Re: 一著名软件公司的java笔试算法题！该如何解决(2)

www.MyException.Cn  网友分享于：2013-01-29  浏览：15次

private boolean[] visited = new boolean[n];
private int[][] a = new int[n][n];
private String result = " ";
private TreeSet set = new TreeSet();

public static void main(String[] args) {
new TestQuestion().start();
}

private void start() {

// Initial the map a[][]
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
a[i][j] = 0;
} else {
a[i][j] = 1;
}
}
}

// 3 and 5 can not be the neighbor.
a[3][5] = 0;
a[5][3] = 0;

// Begin to depth　search.
for (int i = 0; i < n; i++) {
this.depthFirstSearch(i);
}

// Print result treeset.
Iterator it = set.iterator();
while (it.hasNext()) {
String string = (String) it.next();
// "4 " can not be the third position.
if (string.indexOf( "4 ") != 2) {
System.out.println(string);
}
}
}

private void depthFirstSearch(int startIndex) {
visited[startIndex] = true;
result = result + b[startIndex];
if (result.length() == n) {
// Filt the duplicate value.
}
for(int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
} else {
continue;
}
}

// restore the result value and visited value after listing a node.
result = result.substring(0, result.length() -1);
visited[startIndex] = false;
}
}
3，5不能相连：实际要求这个连通图的结点3，5之间不能连通, 可在构造图结构时就满足改条件，然后再遍历图。

// 3 and 5 can not be the neighbor.
a[3][5] = 0;
a[5][3] = 0;

------解决方案--------------------

------解决方案--------------------

import java.util.*;
public class test {
public static void main(String[] arg) {
Scanner r=new Scanner(System.in);
String s=r.nextLine();
Pailie(s, " ");
}
static void Pailie(String s, String p) {
if(s.length() <1) {
String t=p+s;
if(t.charAt(2)!= '4 ' && t.contains( "35 ")==false)
System.out.println(t);
}
else {
for(int i=0; i <s.length(); i++) {
Pailie(s.substring(1),p+s.substring(0,1));
s=s.substring(1)+s.substring(0,1);
}
}
}
}
------解决方案--------------------

http://community.csdn.net/Expert/topic/5201/5201506.xml?temp=.5158502
------解决方案--------------------

------解决方案--------------------

------解决方案--------------------

------解决方案--------------------