//主要看getLInkedCount方法怎么实现的就行,你可以自己运行一下看看结果。亲测
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
public class test {
private static final int xBound = 10;
private static final int yBound = 10;
private static int a[][] = new int[10][10];
private static ArrayList<Integer> xTrack;
private static ArrayList<Integer> yTrack;
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/
public static void main(String[] args) {
printFSameColor();
}
public static void printFSameColor(){
Random random = new Random();
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
a[i][j] = random.nextInt(100)%4;
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println("****************************************************");
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
for(int k=0; k<4; k++){
for(int h=0; h<4; h++){
xTrack = new ArrayList<Integer>();
yTrack = new ArrayList<Integer>();
int temp1 = getLinkedCount(i,j,k,1,h);
if(temp1>=5){
print();
}
}
}
}
System.out.println();
}
}
public static void print(){
int index = 0;
while(!xTrack.isEmpty()){
int x = xTrack.remove(index);
int y = yTrack.remove(index);
System.out.println("x = " + x + " y=" + y);
System.out.println(a[x][y] + " ");
}
System.out.println();
}
/**
* 然后从落子的地方开始判断4个方向是否是同颜色的。分别是-,/,|,\,分别以数字0,1,2,3为参数,往前查找时带参数-1,每找到一个就把返回值-1,往后查找时带参数1,每找到一个将返回值加1。方法声明为:
* 如果没有找到相连的子,返回0,否则返回相连子的个数(和forward符号相同)
* @xpos : 当前子位置x
* @ypos :
* @direction : 当前方向
* @forward : -1表示向前,1表示向后(往前表示X值增加)
* @color : 表示己方的颜色是否为黑子
*/
private static int getLinkedCount(int xpos, int ypos, int direction, int forward, int color) {
// | 时x值不变
int tXpos = (direction == 0) ? xpos : xpos + forward;
// -时y值不变, /时y值减少
int tYpos = (direction == 2) ? ypos : ypos + ((direction == 1) ? -forward : forward);
// 超出了边界
if (tXpos < 0 || tYpos < 0 || tXpos > xBound || tYpos > yBound) {
return 0;
}
// 取得颜色
int tColor = a[xpos][ypos];
if (tColor == color) {
// 颜色相等时,递归取得相连的个数
xTrack.add(xpos);
yTrack.add(ypos);
return 1 + getLinkedCount(tXpos, tYpos, direction, forward, color);
}
return 0;
}
}