leetcode 688. "horse" probability on the board

Subject description:

Given a NxN chess board, chessboard row and column numbers are zero-based. I.e., the upper left corner of the grid as (0, 0), the lower right corner is referred to as a (N-1, N-1). 

An existing "horse" (also translated as "Knight") located at (r, c), K times and intend to move. 

, The chess "Ma" at each step to move below the horizontal or vertical direction in FIG. 2 lattice, a lattice is then moved again to the direction perpendicular thereto, a total of eight optional positions.

 

 

 

Analysis of ideas:

1 idea: first thought is to use dfs, but this time out, the worst that could reach the 100th 8.

2 ideas: D dp, dp [i] [j] [k] represents the probability of moving to change the k-th point is still located on the board at the point (i, j). First, the initial condition dp [i] [j] [0] = 1. The next four cycles, a move to the outermost layer of k times, followed by location i, j of the double loop, the circulating movement direction finally 1 to 8, dp [i] [j] [num] = sum (dp [i] [j] [num-1] * (1.0 / 8.0)), i.e. the current point k times the probability of all probabilities and k-1 times.

 

Code:

 1 class Solution {
 2 public:
 3     double knightProbability(int N, int K, int r, int c) {
 4         if(K<=0)
 5             return 1.0;
 6         if(N<0 || r<0 || r>=N || c<0 || c>=N)
 7             return 0.0;
 8         double dp[26][26][101];
 9         int direction[][2] = {{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}};
10         for(int i=0; i<N; i++)
11             for(int j=0; j<N; j++)
12                 dp[i][j][0]=1;
13         for(int num=1; num<=K; num++)
14         {
15             for(int i=0; i<N; i++)
16             {
17                 for(int j=0; j<N; j++)
18                 {
19                     double tmp = 0;
20                     for(int l=0; l<8; l++)
21                     {
22                         int x = i+direction[l][0];
23                         int y = j+direction[l][1];
24                         if(x<0 || y<0 || x>=N || y>=N)
25                             continue;
26                         tmp += (1.0/8.0)*dp[x][y][num-1];
27                     }
28                     dp[i][j][num] = tmp;
29                 }
30             }
31         }
32         return dp[r][c][K];
33     }
34 };

 

Guess you like

Origin www.cnblogs.com/LJ-LJ/p/11323361.html