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

Java二维数组地图元素征服问题:无法完成全区域征服求助

问题分析与解决方案

原代码核心问题

  • 方向固定:horizontal_direction和vertical_direction仅初始化一次,征服者只会朝单一方向移动,碰到边界就停滞,无法遍历所有区域。
  • 循环次数不足:外层循环仅执行map.length次(5次),远不足以完成25个格子的征服。
  • 追踪逻辑低效:每次遍历整个地图找征服者位置,且找到后直接break,无法持续处理后续移动。

修正后的代码

import java.util.Random;

public class TakingOver {
    public static void main(String[] args) {
        int[][] map = {{0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}};
        int conqueror = 1;
        Random random = new Random();
        
        // 初始化征服者的初始位置
        int currRow = 1, currCol = 2;
        
        // 循环直到所有区域被征服(没有0)
        while (hasZero(map)) {
            // 标记当前位置为已征服
            map[currRow][currCol] = 2;
            
            int newRow, newCol;
            // 随机选择有效方向(上下左右),直到找到可移动的位置
            do {
                int direction = random.nextInt(4); // 0:上,1:下,2:左,3:右
                newRow = currRow;
                newCol = currCol;
                
                switch (direction) {
                    case 0: newRow--; break;
                    case 1: newRow++; break;
                    case 2: newCol--; break;
                    case 3: newCol++; break;
                }
                // 检查新位置是否在边界内且是未征服的0
            } while (newRow < 0 || newRow >= map.length || newCol < 0 || newCol >= map[0].length || map[newRow][newCol] != 0);
            
            // 移动征服者到新位置
            map[newRow][newCol] = conqueror;
            currRow = newRow;
            currCol = newCol;
            
            // 打印当前地图状态
            printMap(map);
            System.out.println("---------------------");
        }
        
        System.out.println("所有区域已被征服!");
    }
    
    // 检查地图中是否还有未征服的0
    private static boolean hasZero(int[][] map) {
        for (int[] row : map) {
            for (int cell : row) {
                if (cell == 0) {
                    return true;
                }
            }
        }
        return false;
    }
    
    // 打印地图
    private static void printMap(int[][] map) {
        for (int[] row : map) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }
    }
}

关键改进说明

  1. 动态追踪位置:直接记录征服者的当前坐标currRow和currCol,无需每次遍历整个地图查找,提升效率。
  2. 循环终止条件:通过hasZero方法判断是否还有未征服区域,确保直到所有格子被征服才停止。
  3. 随机有效方向:每次移动前随机选择上下左右四个方向,若当前方向无效(出界或目标位置非0),则重新随机,保证征服者总能移动到未征服区域。
  4. 清晰的职责拆分:将检查0、打印地图的逻辑抽成独立方法,代码更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:00:56