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

Leetcode骑士巡游配置校验:代码仅通过1024/1026用例求排查

Leetcode Check Knight Tour Configuration 解题问题排查

我在完成Leetcode的Check Knight Tour Configuration题目时,编写了一段Java代码,但提交后仅通过1024/1026个测试用例。手动验证出错的测试用例后,我认为自己的逻辑正确,怀疑是否遗漏了某些细节,附上代码及出错用例截图,希望找出问题所在。

import java.lang.Math;

class Solution {
    public boolean checkValidGrid(int[][] grid) {
        int index = 0;
        int length = grid.length;
        int[][] board = new int[length][length];

        for(int i = 0; i < length; i++){
            for(int j = 0; j < length; j++){
                board[i][j] = index;
                index++;
            }
        }

        for(int i = 0; i < length; i++){
            for(int j = 0; j < length; j++){
                if(i == length - 1 && j == length - 1) break;
                int[] StartingLocation = FindLocation(board[i][j], grid);
                int[] EndingLocation = FindLocation(board[i][j] + 1, grid);

                boolean test = ValidDesination(StartingLocation,EndingLocation,board);
                if(test == false) return false;
            }
        }
        return true;
    }

    public boolean ValidDesination(int[] startingLocation, int[] endingLocation, int[][] board){
        try{if(board[startingLocation[0] - 2][startingLocation[1] + 1] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        try{if(board[startingLocation[0] - 2][startingLocation[1] - 1] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}

        try{if(board[startingLocation[0] + 2][startingLocation[1] + 1] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        try{if(board[startingLocation[0] + 2][startingLocation[1] - 1] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        
        try{if(board[startingLocation[0] - 1][startingLocation[1] + 2] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        try{if(board[startingLocation[0] - 1][startingLocation[1] - 2] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        
        try{if(board[startingLocation[0] + 1][startingLocation[1] + 2] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}
        try{if(board[startingLocation[0] + 1][startingLocation[1] - 2] == board[endingLocation[0]][endingLocation[1]]) return true;}catch(Exception e){}

        return false;
    }

    public int[] FindLocation(int n, int[][] grid){
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid.length; j++){
                if(n == grid[i][j]) return new int[] {i,j};
            }
        }

        return null;
    }
}

出错测试用例截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:23:32