java对角线遍历,Java:如何检查对角线连接二维阵列中的四连胜

I have a Connect Four "board" which is a 6*7 2D char array populated with either spaces, X or O. The win condition is met when there are either four Xs or four Os in a row vertically, horizontally or diagonally. I've managed to get the win conditions checked successfully for vertical and horizontal, where the winning char is returned by some methods as below:

private char CheckVerticalWinner(char[][] currentBoard) {

// check vertical (move down one row, same column)

char vWinner = ' ';

for (int col=0; col<7; col++) {

int vCount = 0;

for (int row=0; row<5; row++) {

if (currentBoard[row][col]!=' ' &&

currentBoard[row][col] == currentBoard[row+1][col]) {

vCount++;

System.out.println("VERT "+vCount); //test

} else {

vCount = 1;

}

if (vCount>=4) {

vWinner = currentBoard[row][col];

}

}

}

return vWinner;

}

private char CheckHorizontalWinner(char[][] currentBoard) {

// check horizontal (move across one column, same row)

char hWinner = ' ';

for (int row=0; row<6; row++) {

int hCount = 0;

for (int col=0; col<6; col++) {

if (currentBoard[row][col]!=' ' &&

currentBoard[row][col] == currentBoard[row][col+1]) {

hCount++;

System.out.println("HORIZ "+hCount); //test

} else {

hCount = 1;

}

if (hCount>= 4) {

hWinner = currentBoard[row][col];

}

}

}

return hWinner;

}

I'm just stuck on how to check for diagonal wins, without throwing an ArrayIndexOutOfBoundsException. I know I need to iterate through the 2D array twice, once for forward diagonals and once for backward diagonals that are 4 squares long or more, like in the below diagram:

Basically, how would I fill in this method to return a winning char?

private char CheckDiagonalWinner(char[][] currentBoard) {

// some iteration here

return dWinner;

}

Any help would be much appreciated!

解决方案

The simplest algorithm probably is:

for every direction

for every coordinate

check whether the next 3 elements in this direction exist and are the same

in code:

final int maxx = 7;

final int maxy = 6;

char winner(char[][] board) {

int[][] directions = {{1,0}, {1,-1}, {1,1}, {0,1}};

for (int[] d : directions) {

int dx = d[0];

int dy = d[1];

for (int x = 0; x < maxx; x++) {

for (int y = 0; y < maxy; y++) {

int lastx = x + 3*dx;

int lasty = y + 3*dy;

if (0 <= lastx && lastx < maxx && 0 <= lasty && lasty < maxy) {

char w = board[x][y];

if (w != ' ' && w == board[x+dx][y+dy]

&& w == board[x+2*dx][y+2*dy]

&& w == board[lastx][lasty]) {

return w;

}

}

}

}

}

return ' '; // no winner

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值