有人能指出我的写作方向吗?我从概念上理解这个问题,但不知道如何实现。
使用以下字段编写一个MatrixNeighbors类:
int rows
int columns
int[][] matrix
以下构造函数:
MatrixNeighbors(int rows, int columns) : sets both the rows and columns fields, then creates a new matrix of size [rows]x[columns].
和以下方法:
String neighbors(int row, int column) : returns a String containing all the cell neighbors of the cell at row, column, starting directly above the specified cell and moving clockwise. If the cell is along any edge, be sure to omit the non-existent neighbors. See below for formatting.
Strings will be formatted as such: “<above cell row>,<above cell column>;<next cell clockwise row>,<next cell clockwise column>;…<last cell row>,<last cell column>;”.
通过返回字符串“cell is not exist”处理不存在的单元格,该单元格存在于矩阵边界之外。
考虑以下图表和代码:
(0,0)(1,0)(2,0)
(0,1)(1,1)(2,1)
(0,2)(1,2)(2,2)
MatrixNeighbors m = new MatrixNeighbors(3, 3);
System.out.println(m.neighbors(0, 0)); //prints "0,1;1,1;1,0;"
System.out.println(m.neighbors(2, 2)); //prints "1,2;2,1;1,1;"
System.out.println(m.neighbors(1, 1)); //prints "0,1;0,2;1,2;2,2;2,1;2,0;1,0;0,0;"
System.out.println(m.neighbors(3, 0)); //prints "cell does not exist"
我有什么:
public class MatrixNeighbors {
int rows = 0;
int columns = 0;
int [][] matrix;
MatrixNeighbors(int row, int column) {
for (int i = 0; i < MatrixNeighbors.length; i++)
for (int j = 0; j < MatrixNeighbors[i].length; j++)
if (i <= row && j <= column)
return (row - 1, column);
}
我相信这现在正在将该位置的位置返回到该位置之上一行,但我不知道如何确保它只返回它,如果该位置在矩阵内,然后如何将该点返回到新地点的权利。
答案 0 :(得分:0)
您可以使用数学来确定身边的人
这没有快速功能。我知道
答案 1 :(得分:0)
您应该能够通过使用try-catch块来检查位置是否有效。例如,以下方法使用try-catch来验证给予方法的位置,然后检查位置是否存在。 在所有情况下,try block将尝试设置一个值到该位置,如果它抛出异常,则表示它不存在,因此它不会添加到字符串中。这将最终向您显示有效的职位。这是我考虑过的最佳方式,但是我非常确定使用循环必须有一种更简单的方法,但是由您来调查。
public String neighbors(int row, int column)
{
String ret = "";
try
{
matrix[row][column] = 0; // To check if the row exists we just set a dummy value.
try { matrix[row][column - 1] = 0; ret += row + "," + (column-1) + ";"; }
catch (Exception e) {}
try { matrix[row - 1][column - 1] = 0; ret += (row-1) + "," + (column-1) + ";"; }
catch (Exception e) {}
try { matrix[row - 1][column] = 0; ret += (row-1) + "," + column + ";"; }
catch (Exception e) {}
try { matrix[row - 1][column + 1] = 0; ret += (row-1) + "," + (column+1) + ";"; }
catch (Exception e) {}
try { matrix[row][column + 1] = 0; ret += row + "," + (column+1) + ";"; }
catch (Exception e) {}
try { matrix[row + 1][column + 1] = 0; ret += (row+1) + "," + (column+1) + ";"; }
catch (Exception e) {}
try { matrix[row + 1][column] = 0; ret += (row+1) + "," + column + ";"; }
catch (Exception e) {}
try { matrix[row + 1][column - 1] = 0; ret += (row+1) + "," + (column-1) + ";"; }
catch (Exception e) {}
}
catch (Exception e)
{
ret += "Cell does not exist."; // Woho, exception caused due to position non-existing in matrix.
}
finally
{
return ret;
}
}