java - 如何检查二维数组中的2个元素是否彼此相邻
问题描述
我试图弄清楚如何接受 2 个整数参数,一个称为“start”的初始整数和一个称为“destination”的第二个整数。我想使用我的方法中的两个参数,首先检查起始整数是否在矩阵内,然后检查目标整数是否在它周围的 4 个元素内相邻 - (北、东、南、西)。
示例 1:
如果起始整数是(6),则检查目标整数(7)是否与起始整数相邻。如果是真的,那就做点什么。
示例 2:
在这种情况下,如果起始整数 = 4 且目标整数 = 2。程序不会认为这些元素是相邻的。
初始化数组:
int[][] matrix = {{0,1,2,},
{3,4,5,},
{6,7,8}};
检查方法:
public static double check(int start, int destination)
{
for(int row = 0; row < matrix.length; row++)
{
for(int col = 0; col < matrix[0].length; col++)
{
// check if the start integer is in the matrix
if(matrix[row][col] == start)
{
// check if destination integer is adjacent to starting integer:
if (destination is adjacent to start)
{
// do something
}
}
}
}
}
请记住,矩阵不会有重复的数字,并且将始终保持不变。
我将如何检查这个?
我花了几个小时查看类似的 StackOverflow 帖子,但我似乎真的无法掌握给出的示例。有人可以指导我完成吗?
解决方案
如果您的start
元素在矩阵中,则有 4 个可能的位置可以检查您的destination
元素:LEFT, RIGHT, UP, DOWN
. 您可以添加一个默认设置为 false 的变量并检查 4 个点,记住不要越界:
public static double check(int start, int destination) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// check if the start integer is in the matrix
if (matrix[row][col] == start) {
// check if destination integer is adjacent to starting integer:
boolean destIsAdj = false;
//left
if (col - 1 > 0 && matrix[row][col-1] == destination)
destIsAdj = true;
//right
else if (col + 1 < matrix[0].length && matrix[row][col+1] == destination)
destIsAdj = true;
//up
else if (row - 1 > 0 && matrix[row-1][col] == destination)
destIsAdj = true;
//down
else if (row + 1 < matrix.length && matrix[row+1][col] == destination)
destIsAdj = true;
if (destIsAdj){
// adjacent! do something
}
else {
// not adjacent! do something else
}
}
}
}
return 0.0;
}
推荐阅读
- css - 如何在 IE 11 中显示:grid div 以占据整个屏幕?(100vh 似乎不起作用)
- html - 为什么我的 HTML 表格不遵守指定的布局?
- web-traffic - 如何在给定时间获得给定网址(不在我的网站上)的多次点击?
- javascript - 如何从 3rd 方 api 中提取数据并使用 javascript 将其显示在我的页面上?
- javascript - 反应将增量数据传递给父级
- agens-graph - 如何在 AgensGraph 上使用“分组依据”查询?
- postgresql - How to ALTER ROLE for many roles?
- javascript - How to select an anchor element based on some text in the URL?
- ios - 丰富的本地通知
- javascript - “未捕获的 TypeError:回调不是函数” - 为什么会这样?