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
相关产品推荐
相关产品推荐

