You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java二维数组中检查指定坐标的相邻元素

解决Java二维数组坐标相邻检查问题

1. 先处理坐标解析

用户输入的F3这类字符串需要转换成二维数组的索引:字母对应列(A=0、B=1…F=5),数字是行号(需转成0起始索引,比如3→2)。示例代码:

// 解析单个坐标字符串,如"F3"
public static int[] parseCoordinate(String coord) {
    char colChar = Character.toUpperCase(coord.charAt(0));
    int col = colChar - 'A'; // 大写字母转列索引
    int row = Integer.parseInt(coord.substring(1)) - 1; // 行号转0起始索引
    return new int[]{row, col};
}

2. 维护标记与禁止区域

用两个集合分别存储已标记的坐标,以及这些坐标的垂直水平相邻禁止区域(上下左右),避免重复判断:

// 存储已标记坐标,用"行,列"字符串作为唯一标识
private static Set<String> markedCoords = new HashSet<>();
// 存储禁止标记的相邻坐标
private static Set<String> forbiddenCoords = new HashSet<>();

3. 生成禁止区域的逻辑

针对已标记的坐标,生成其上下左右四个方向的相邻坐标,同时判断是否在数组边界内:

// 给指定坐标添加垂直水平方向的禁止区域
public static void addForbiddenCoords(int row, int col, int[][] array) {
    // 定义四个方向:上、下、左、右
    int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (int[] dir : directions) {
        int newRow = row + dir[0];
        int newCol = col + dir[1];
        // 检查是否在数组合法范围内
        if (newRow >= 0 && newRow < array.length && newCol >= 0 && newCol < array[0].length) {
            forbiddenCoords.add(newRow + "," + newCol);
        }
    }
}

4. 完整业务逻辑示例

整合所有步骤,处理用户输入并做合法性校验:

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class GridMarker {
    private static Set<String> markedCoords = new HashSet<>();
    private static Set<String> forbiddenCoords = new HashSet<>();

    public static void main(String[] args) {
        // 示例:8行6列的网格(对应A-F列,1-8行)
        int[][] grid = new int[8][6];
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("输入坐标(格式如F3 F7,输入quit退出):");
            String input = scanner.nextLine().trim();
            if ("quit".equalsIgnoreCase(input)) break;

            String[] coords = input.split(" ");
            for (String coordStr : coords) {
                int[] coord = parseCoordinate(coordStr);
                int row = coord[0];
                int col = coord[1];
                String key = row + "," + col;

                // 合法性校验
                if (markedCoords.contains(key)) {
                    System.out.println("坐标" + coordStr + "已标记,跳过");
                    continue;
                }
                if (forbiddenCoords.contains(key)) {
                    System.out.println("坐标" + coordStr + "与已标记坐标相邻,禁止标记");
                    continue;
                }

                // 标记坐标并更新禁止区域
                markedCoords.add(key);
                grid[row][col] = 1; // 用1标记已选择的位置
                addForbiddenCoords(row, col, grid);
                System.out.println("成功标记坐标" + coordStr);
            }
        }
        scanner.close();
    }

    public static int[] parseCoordinate(String coord) {
        char colChar = Character.toUpperCase(coord.charAt(0));
        int col = colChar - 'A';
        int row = Integer.parseInt(coord.substring(1)) - 1;
        return new int[]{row, col};
    }

    public static void addForbiddenCoords(int row, int col, int[][] array) {
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (int[] dir : directions) {
            int newRow = row + dir[0];
            int newCol = col + dir[1];
            if (newRow >= 0 && newRow < array.length && newCol >= 0 && newCol < array[0].length) {
                forbiddenCoords.add(newRow + "," + newCol);
            }
        }
    }
}

对你提供的代码的说明

你找到的代码是遍历整个数组的每个元素的所有相邻位置(包括对角线),但你的需求是针对单个特定坐标检查垂直水平相邻区域,因此不需要嵌套遍历整个数组。用方向数组+边界判断的方式,比原代码更简洁且贴合需求。

内容的提问来源于stack exchange,提问作者Razvan Calina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:48:21