测试连通性问题.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.Random;
public class ConnectionPanel extends JPanel {
/**
* 默認構造的變量,避免警告出現.
* 有無對程序無影響.
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
for(int i=distence;i<=width;i+=distence)
for(int k=distence;k<=height;k+=distence){
//圆点绘制,i,k表示位置坐标(x,y),radio 表示圆点的半径.
Ellipse2D ellipse = new Ellipse2D.Double(i,k,radio,radio);
g2.fill(ellipse);
g2.draw(ellipse);
}
//随机生成0和1
for(int i=0;i<count;i++)
{
Random rand = new Random();
N[i]=rand.nextInt(2);
if(N[i]==0)
pt0++;
else
pt1++;
}
int nSIZE=(int)(count*prob);
while(pt1<nSIZE)//随机选取0的数值,将其强制改为1
{
int k;
do{
Random rand = new Random();
k=rand.nextInt(count);
}while(N[k]!=0);//直到找到一个数组元素为0的值时,退出循环
N[k]=1;//将其强制改为1
pt0--;
pt1++;
}
while(pt1>nSIZE)//随机选取1的数值,将其强制改为0
{
int k;
do{
Random rand = new Random();
k=rand.nextInt(count);
}while(N[k]!=1);//直到找到一个数组元素为0的值,退出循环
N[k]=0;
pt0++;
pt1--;
}
g2.setBackground(Color.cyan);
//按照数组随即的对横排画线
for (int j = 0; j < (height/ distence ); j++)
for (int m = 0; m < width / distence - 1; m++)
{
startX=distence*(m+1);
startY=distence*(j+1);
endX=distence*(m+2);
endY=startY;
if(N[j*(width/distence-1)+m]==1){//若为1,则表示随即生成线段
g2.draw(new Line2D.Double(startX,startY,endX,endY));//画线
}
else
continue;
}
for(int j=0;j<width/distence;j++)
for(int m=0;m<height/distence-1;m++)
{
startX=distence*(j+1);
startY=distence*(m+1);
endX=startX;
endY=distence*(m+2);
if(N[j*(height/distence-1)+m+count/2]==1){//若为1,则表示随即生成线段
g2.draw(new Line2D.Double(startX,startY,endX,endY));//画线
}
else
continue;
}
}//paintComponent()结束
private static int radio=1;//圓點的半徑.
private static int distence=8;//兩個點之間的距離.單位為像素.
private static double prob=0.4;//概率
//畫點的寬度和高度.width/10=橫排的點的數目.height/10=豎排的點的數目.
private static int width = 450;
private static int height =450;
//count 表示當prob=1的時候,可能的邊.
private static int count=(width/distence-1)*height/distence+(height/distence-1)*width/distence;
//0,1 的數目一共有多少.
private static int pt0=0;
private static int pt1=0;
//一條線段的起點和終點.
private static int startX;
private static int endX;
private static int startY;
private static int endY;
private static int[] N=new int[count];
}
以上是本人写的Panel类,其功能只是随机的画出来线.
但是需要知道如何对线进行遍历.
只要有两个点相连,就说明连同,然后进行颜色改变.
效果如下.