-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackTracking.cs
More file actions
90 lines (76 loc) · 2.67 KB
/
BackTracking.cs
File metadata and controls
90 lines (76 loc) · 2.67 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Bruteforce solution
using System;
using System.Collections.Generic;
public class Solution {
int ROWS, COLS;
int[][] directions = new int[][] {
new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1}
};
public char[][] GangaYamuna(int[][] heights) {
ROWS = heights.Length;
COLS = heights[0].Length;
// Initialize result matrix
char[][] result = new char[ROWS][];
for (int i = 0; i < ROWS; i++) {
result[i] = new char[COLS];
}
// Check reachability for each cell
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
bool ganga = false, yamuna = false;
Dfs(heights, r, c, int.MaxValue, ref ganga, ref yamuna);
if (ganga && yamuna) {
result[r][c] = 'M'; // Merge point
} else if (ganga) {
result[r][c] = 'G'; // Ganga only
} else if (yamuna) {
result[r][c] = 'Y'; // Yamuna only
}
}
}
return result;
}
private void Dfs(int[][] heights, int r, int c, int prevHeight, ref bool ganga, ref bool yamuna) {
// Termination conditions
if (r < 0 || c < 0) {
ganga = true; // Reached Ganga boundary
return;
}
if (r >= ROWS || c >= COLS) {
yamuna = true; // Reached Yamuna boundary
return;
}
if (heights[r][c] > prevHeight) {
return; // Elevation constraint
}
// Temporarily mark the cell as visited
int tmp = heights[r][c];
heights[r][c] = int.MaxValue;
// Explore all four directions
foreach (var dir in directions) {
Dfs(heights, r + dir[0], c + dir[1], tmp, ref ganga, ref yamuna);
if (ganga && yamuna) {
break; // Stop further exploration if both rivers are reachable
}
}
// Restore the cell's value
heights[r][c] = tmp;
}
public static void Main(string[] args) {
// Input heights matrix
int[][] heights = new int[][] {
new int[] {1, 2, 2, 3, 5},
new int[] {3, 2, 3, 4, 4},
new int[] {2, 4, 5, 3, 1},
new int[] {6, 7, 1, 4, 5},
new int[] {5, 1, 1, 2, 4}
};
Solution solution = new Solution();
char[][] result = solution.GangaYamuna(heights);
// Output the result matrix
Console.WriteLine("Result Matrix:");
for (int r = 0; r < result.Length; r++) {
Console.WriteLine(string.Join(" ", result[r]));
}
}
}