检查二维数组是否对称java,更有效的方法来检查Java中二维数组中的邻居

Hey all, for a few of my college assignments I've found the need to check neighbouring cells in 2-dimensional arrays (grids). The solution I've used is a bit of a hack using exceptions, and I'm looking for a way to clean it up without having loads of if statements like some of my classmates. My current solution is

for ( int row = 0; row < grid.length; row++ ) {

for ( int col = 0; col < grid.length; col++ ) {

// this section will usually be in a function

// checks neighbours of the current "cell"

try {

for ( int rowMod = -1; rowMod <= 1; rowMod++ ) {

for ( int colMod = -1; colMod <= 1; colMod++ ) {

if ( someVar == grid[row+rowMod][col+colMod] ) {

// do something

}

}

}

} catch ( ArrayIndexOutOfBoundsException e ) {

// do nothing, continue

}

// end checking neighbours

}

}

I shudder to think of the inefficiency using exceptions to get my code to work causes, so I'm looking for suggestions as to how I could remove the reliance on exceptions from my code without sacrificing readability if it's possible, and just how I could make this code segment generally more efficient. Thanks in advance.

解决方案

You can try this.

First decide the size of the grid Lets say its 8 X 8 & assign MIN_X = 0, MIN_Y = 0, MAX_X =7, MAX_Y =7

Your curren position is represented by thisPosX , thisPosY, then try this:

int startPosX = (thisPosX - 1 < MIN_X) ? thisPosX : thisPosX-1;

int startPosY = (thisPosY - 1 < MIN_Y) ? thisPosY : thisPosY-1;

int endPosX = (thisPosX + 1 > MAX_X) ? thisPosX : thisPosX+1;

int endPosY = (thisPosY + 1 > MAX_Y) ? thisPosY : thisPosY+1;

// See how many are alive

for (int rowNum=startPosX; rowNum<=endPosX; rowNum++) {

for (int colNum=startPosY; colNum<=endPosY; colNum++) {

// All the neighbors will be grid[rowNum][colNum]

}

}

you can finish it in 2 loops.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值