using
System;
using
System.Collections.Generic;
class
GFG {
static
List<List<
char
> > possibleWays;
static
bool
shouldSwap(
char
[] str,
int
start,
int
curr)
{
for
(
int
i = start; i < curr; i++) {
if
(str[i] == str[curr]) {
return
false
;
}
}
return
true
;
}
static
void
findPermutations(
char
[] str,
int
index,
int
n)
{
if
(index >= n) {
List<
char
> l =
new
List<
char
>();
foreach
(
char
ch
in
str) l.Add(ch);
possibleWays.Add(l);
return
;
}
for
(
int
i = index; i < n; i++) {
bool
check = shouldSwap(str, index, i);
if
(check) {
swap(str, index, i);
findPermutations(str, index + 1, n);
swap(str, index, i);
}
}
}
static
void
swap(
char
[] str,
int
i,
int
j)
{
char
c = str[i];
str[i] = str[j];
str[j] = c;
}
static
void
minCost(
int
[][] grid,
int
N)
{
List<
char
> moveList =
new
List<
char
>();
grid[0][0] = 0;
List<
int
> possibleWaysSum =
new
List<
int
>();
for
(
int
k = 0; k < N - 1; k++) {
moveList.Add(
'i'
);
moveList.Add(
'j'
);
possibleWays =
new
List<List<
char
> >();
int
n = moveList.Count;
char
[] str =
new
char
[n];
for
(
int
i = 0; i < n; i++)
str[i] = moveList[i];
findPermutations(str, 0, n);
possibleWaysSum =
new
List<
int
>();
foreach
(List<
char
> way
in
possibleWays)
{
int
i = 0, j = 0, tempSum = 0;
foreach
(
char
move
in
way)
{
if
(move ==
'i'
) {
i += 1;
}
else
{
j += 1;
}
tempSum
= (
int
)(tempSum / 2) + grid[i][j];
}
possibleWaysSum.Add(tempSum);
}
}
int
ans = possibleWaysSum[0];
for
(
int
i = 1; i < possibleWaysSum.Count; i++)
ans = Math.Min(ans, possibleWaysSum[i]);
Console.WriteLine(ans);
}
public
static
void
Main(
string
[] args)
{
int
N = 4;
int
[][] grid
= {
new
[] { 0, 3, 9, 6 },
new
[] { 1, 4, 4, 5 },
new
[] { 8, 2, 5, 4 },
new
[] { 1, 8, 5, 9 } };
minCost(grid, N);
}
}