aboutsummaryrefslogtreecommitdiff
path: root/knight_probability_chessboard.c
blob: 63a678dac5fa38a1d1bca862aa65a08bfefae190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 688. Knight Probability in Chessboard
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * on an 'n x n' chessboard, a knight starts at the cell '(row, column)' and
 * attempts to make exactly 'k' moves. the rows and columns are 0-indexed, so
 * the top-left cell is '(0, 0)', and the bottom-right cell is '(n - 1, n - 1)'.
 * a chess knight has eight possible moves it can make, as illustrated below
 * [see image]. each move is two cells in a cardinal direction, then one cell in
 * an orthogonal direction.
 */

bool in_bound(int row, int col, int n) {
  return 0 <= row && row < n && col >= 0 && col < n;
}

double knightProbability(int n, int k, int row, int col) {
  double **a = (double **)malloc(sizeof(double *) * n);
  double **b = (double **)malloc(sizeof(double *) * n);
  for (int i = 0; i < n; i++) {
    a[i] = (double *)malloc(sizeof(double) * n);
    b[i] = (double *)malloc(sizeof(double) * n);
    for (int j = 0; j < n; j++) {
      a[i][j] = 0;
      b[i][j] = 0;
    }
  }
  static int dr[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
  static int dc[8] = {-2, -1, 1, 2, -2, -1, 1, 2};
  a[row][col] = 1;
  double **to = a;
  double **from = NULL;
  for (int step = 1; step <= k; step++) {
    to = ((step % 2) != 0 ? b : a);
    from = ((step % 2) != 0 ? a : b);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        to[i][j] = 0;
        for (int l = 0; l < 8; l++) {
          to[i][j] += in_bound(i + dr[l], j + dc[l], n)
                          ? from[i + dr[l]][j + dc[l]] / 8
                          : 0;
        }
      }
    }
  }
  double ans = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      ans += to[i][j];
  for (int i = 0; i < n; i++)
    free(a[i]), free(b[i]);
  free(a), free(b);
  return ans;
}

int main() {
  printf("%f\n", knightProbability(3, 2, 0, 0)); // expect: 0.06250
  printf("%f\n", knightProbability(1, 0, 0, 0)); // expect: 1.00000
}