Problem
There is a knight on an n x n
chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once.
You are given an n x n
integer matrix grid
consisting of distinct integers from the range [0, n * n - 1]
where grid[row][col]
indicates that the cell (row, col)
is the grid[row][col]th
cell that the knight visited. The moves are 0-indexed.
Return true
if grid
represents a valid configuration of the knight's movements or false
otherwise.
Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.
Example 1:
Input: grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
Output: true
Explanation: The above diagram represents the grid. It can be shown that it is a valid configuration.
Example 2:
Input: grid = [[0,3,6],[5,8,1],[2,7,4]]
Output: false
Explanation: The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 7
0 <= grid[row][col] < n * n
- All integers in
grid
are unique.
Solution (Java)
class Solution {
static void isValid(int grid[][],boolean visited[][],int v1,int v2,int move,int r,int c){
if(v1<0 || v2<0 ||v1>=r || v2>=c)return;
if(!visited[v1][v2]&& grid[v1][v2]==move ){
visited[v1][v2]=true;
isValid(grid,visited,v1+1,v2+2,move+1,r,c);
isValid(grid,visited,v1+1,v2-2,move+1,r,c);
isValid(grid,visited,v1-1,v2+2,move+1,r,c);
isValid(grid,visited,v1-1,v2-2,move+1,r,c);
isValid(grid,visited,v1+2,v2+1,move+1,r,c);
isValid(grid,visited,v1-2,v2+1,move+1,r,c);
isValid(grid,visited,v1+2,v2-1,move+1,r,c);
isValid(grid,visited,v1-2,v2-1,move+1,r,c);
}
}
public boolean checkValidGrid(int[][] grid) {
int r=grid.length,c=grid[0].length;
boolean visited[][]=new boolean[r][c];
isValid(grid,visited,0,0,0,r,c);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
if(!visited[i][j])return false;
return true;
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).