Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jianminchen/0154704a3e123369492fa78ae10530ac to your computer and use it in GitHub Desktop.
Save jianminchen/0154704a3e123369492fa78ae10530ac to your computer and use it in GitHub Desktop.
Leetcode 688 - Knight probability in chessboard - pass Leetcode 688 online judge
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode688KnightProbabilityInChessboard
{
/// <summary>
/// Leetcode 688 - Knight probablity in chessboard
/// source code is based on the discussion:
/// https://leetcode.com/problems/knight-probability-in-chessboard/discuss/108181/My-accepted-DP-solution?page=2
/// </summary>
class Program
{
static void Main(string[] args)
{ // 3, 2, 0, 0
var test = knightProbability(3, 2, 0, 0);
}
/// <summary>
/// code review Julia March 12, 2018
/// How to understand the dynamic programming idea to solve the problem?
///
/// </summary>
/// <param name="size"></param>
/// <param name="kSteps"></param>
/// <param name="startRow"></param>
/// <param name="startCol"></param>
/// <returns></returns>
public static double knightProbability(int size, int kSteps, int startRow, int startCol)
{
var moves = new int[][] { new int[] { 1, 2 }, new int[] { 1, -2 }, new int[] { 2, 1 }, new int[] { 2, -1 },
new int[] { -1, 2 }, new int[] { -1, -2 }, new int[] { -2, 1 }, new int[] { -2, -1 } };
var dp0 = new double[size, size];
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
dp0[row, col] = 1;
}
}
for (int step = 0; step < kSteps; step++)
{
var dp1 = new double[size, size];
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
foreach (int[] move in moves)
{
var currentRow = row + move[0];
var currentCol = col + move[1];
if (isLegal(currentRow, currentCol, size))
{
dp1[currentRow, currentCol] += dp0[row, col];
}
}
}
}
arrayCopy(dp1, dp0);
}
return dp0[startRow, startCol] * 1.0 / Math.Pow(8, kSteps);
}
private static void arrayCopy(double[,] source, double[,] destination)
{
int rows = source.GetLength(0);
int columns = source.GetLength(1);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
destination[row, col] = source[row, col];
}
}
}
private static bool isLegal(int r, int c, int len)
{
return r >= 0 && r < len && c >= 0 && c < len;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment