java - 在多维数组中查找坐标
问题描述
我有一个int[][]
像这样的数组:
int[][] arr = { {3, 4, 3, 5, -9},
{0, 4, 4, -8, 6},
{1, 1, 3, -9, 6},
{4, 3, -2, 5, 6}};
实际问题是在二维数组中找到一个矩形,矩形的每个角与二维数组中的角元素具有相同的值。例如,角是 3、-9、4 和 6。生成的矩形是 [0, 2]、[0, 4]、[1, 2]、[1, 4] 处的那个。
我的尝试是首先找出每行所有 [3, -9] 的位置,例如,第一行在 [{0,0},{0,4}] 和 [ {0,2},{0,4}]。
我可以执行标准的嵌套for
循环来查找每个 3 和每个 9:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
// if value is 3, store the co-ordinates
// if value is 9, store the co-ordinates (separately)
}
}
但后来我被迫遍历 2 个列表(3 和 -9 的)并检查每个 3 是否在同一行上有一个 -9,并且它在该行的后面,如果是这样,将两个坐标组合并存储在一起。
然后当然我必须对 4s 和 6s 做同样的事情,它很快就变得一团糟。
也许我在看这一切都是错误的,并且可以被认为是XY Problem。
我的问题:如何在二维数组中找到一个矩形,该矩形的角与二维数组的外角匹配?
解决方案
普通搜索呢?
public static List<Point> findRectangle(int[][] arr) {
int height = arr.length;
int width = arr[0].length;
for (int rowTop = 0; rowTop < height - 1; rowTop++) {
for (int colLeft = rowTop == 0 ? 1 : 0; colLeft < width - 1; colLeft++) {
// find new left-top corner
if (arr[rowTop][colLeft] != arr[0][0])
continue;
int colRight = colLeft + 1;
while (colRight < width && arr[rowTop][colRight] != arr[0][width - 1]) {
colRight++;
}
if (colRight == width)
continue;
// find new left-bottom corner
int rowBottom = rowTop + 1;
while (rowBottom < height && arr[rowBottom][colLeft] != arr[height - 1][0]) {
rowBottom++;
}
if (rowBottom == height || arr[rowBottom][colRight] != arr[height - 1][width - 1])
continue;
return Arrays.asList(
new Point(rowTop, colLeft),
new Point(rowTop, colRight),
new Point(rowBottom, colLeft),
new Point(rowBottom, colRight));
}
}
return Collections.emptyList();
}
public static final class Point {
private final int row;
private final int col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
}
推荐阅读
- sql - 如何根据两个条件对列求和,一个基于字段值,另一个基于检索到的记录值?
- amazon-s3 - 我可以生成一个包含 s3-select 表达式的预签名 s3 url 吗?
- javascript - 如何在 Chrome 中成功更新 .then 函数中的 HTML 音频播放器源
- spring-boot - JSP、静态内容、SpringBoot jar 和 IntelliJ
- python - 哪种方法可以将 UTC 格式的字符串转换为日-月-年字符串?
- c# - 如何处理依赖注入创建的 ILogger Scope
- c# - C# Winform:验证 GridDataView 单元格值时出现空异常错误
- ruby-on-rails - Puma 在 docker 容器内默默退出
- r - 基于可以出现在各个行中的唯一 ID 号在 r 中使用 data.table 进行转换
- javascript - 为什么 document.activeElement 在使用 Firefox 的 Mac 上会产生不同的结果