【发布时间】:2018-02-28 01:44:29
【问题描述】:
我想知道是否有更简单的方法可以做到这一点?该项目要求我编写此方法,该方法使用另一种方法,如果那里有宝藏,则返回 true 或 false 的布尔值。我把那个方法记下来了,但它现在要我写一个方法,返回有多少宝藏位于相邻(在所有方向)到行和列中的设定位置。我把它画在一张纸上,然后得出了……这个。但是,我觉得我在重复代码,但我不明白任何其他可以满足条件的方式。我希望它更简洁……我在想 2 个 for 循环?但是有两个条件在 for 循环中不起作用。
//precondition: 0<=row<rows in map and 0<=col<cols in map
//postcondition: returns a count of the number of treasures in the cells adjacent to the location row,col
//horizontally, vertically, and diagonally.
public int numAdjacent(int row, int col) {
if(hasTreasure(row,col)) {
return -1;
}
int numOfTreasure = 0;
if ((0<=row && row < mapHeight()) && (0<=col && col < mapWidth())) {
if(hasTreasure(row - 1,col - 1)) {
numOfTreasure++;
}
}
if (0<=row && row < mapHeight()) {
if(hasTreasure(row - 1,col)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row - 1,col + 1)) {
numOfTreasure++;
}
}
if (0<=row && row < mapHeight()) {
if(hasTreasure(row + 1,col)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row + 1,col + 1)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row + 1,col - 1)) {
numOfTreasure++;
}
}
if (0<=col && col < mapWidth()) {
if(hasTreasure(row,col + 1)) {
numOfTreasure++;
}
}
if (0<=col && col < mapWidth()) {
if(hasTreasure(row,col - 1)) {
numOfTreasure++;
}
}
return numOfTreasure;
}
【问题讨论】:
-
如果当前坐标有宝物,为什么要立即返回
-1?如果这很重要,我会修改我的答案以反映这一点。 -
是的,因为 hasTreasure 是这样的:
public boolean hasTreasure(int row, int col) { if(row>map.length || col> map[0].length || row < 0 && col < 0) { throw new IllegalArgumentException("out of bounds on map"); } return map[row][col]; }但由于某种原因,这也给了我一个错误。 -
这并不能解释为什么你会返回
-1,尽管如果它有宝藏位于那个坐标。 -
我认为这是一种跳过它的方法,我对这样的代码有点陌生..它不会添加任何东西到宝藏和跳过吗?
-
谢谢!!现在它完美运行,我吓坏了这么久。