如何实现在一个100*100的格子里面随机分布50个不重复的点,且保证每个点周围的8个点没有其他点的存在,谢谢。
------解决方案--------------------
保证每个点周围的8个点没有其他点的存在
===============
边角格子周围没有8个点怎么办?
这个问题应该是类似八皇后问题吧,算法什么的不太清楚,坐等高人
------解决方案--------------------
- Java code
import java.util.Random;public class RandomTest8 { private boolean[][] table; private final int size = 100; private int count; public RandomTest8(){ table = new boolean[size+2][size+2]; count = 0; } public void print(){ for(int i=1;i<size+1;i++){ for(int j=1;j<size+1;j++){ System.out.print(table[i][j]+"\t"); } System.out.println(); } } public boolean insert(){ Random ran = new Random(); int i = ran.nextInt(size)+1; int j = ran.nextInt(size)+1; if(!table[i][j] && !table[i][j-1] && !table[i][j+1] && !table[i-1][j] && !table[i-1][j-1] && !table[i-1][j+1] && !table[i+1][j] && !table[i+1][j-1] && !table[i+1][j+1]){ table[i][j] = true; return true; } return false; } public void test(){ while(count<8){ if(insert()) count++; } print(); } public static void main(String[] args){ RandomTest8 r = new RandomTest8(); r.test(); }}
------解决方案--------------------
- Java code
import java.util.Random;public class RandomTest8 { private boolean[][] table; private final int size = 100; private int count; public RandomTest8(){ table = new boolean[size+2][size+2]; count = 0; } public void print(){ for(int i=1;i<size+1;i++){ for(int j=1;j<size+1;j++){ System.out.print(table[i][j]+"\t"); } System.out.println(); } } public boolean insert(){ Random ran = new Random(); int i = ran.nextInt(size)+1; int j = ran.nextInt(size)+1; if(!table[i][j] && !table[i][j-1] && !table[i][j+1] && !table[i-1][j] && !table[i-1][j-1] && !table[i-1][j+1] && !table[i+1][j] && !table[i+1][j-1] && !table[i+1][j+1]){ table[i][j] = true; return true; } return false; } public void test(){ //刚这里点数插错了 while(count<50){ if(insert()) count++; } print(); } public static void main(String[] args){ RandomTest8 r = new RandomTest8(); r.test(); }}