You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>

typedef struct Graph {


int V;
int **adj;
} Graph;

Graph* createGraph(int V) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->adj = (int**)malloc(V * sizeof(int*));
for (int i = 0; i < V; i++) {
graph->adj[i] = (int*)malloc(V * sizeof(int));
for (int j = 0; j < V; j++) {
graph->adj[i][j] = 0; // Initialize with 0 (no edge)
}
}
return graph;
}

void addEdge(Graph* graph, int v, int w, int weight) {


graph->adj[v][w] = weight;
graph->adj[w][v] = weight; // Assuming the graph is undirected
}

int BFS(Graph* graph) {


int s = 0;
bool visited[graph->V];
int distance[graph->V];
int parent[graph->V];
for (int i = 0; i < graph->V; i++) {
visited[i] = false;
parent[i] = -1;
distance[i] = INT_MAX; // Initialize distances to infinity
}
int* Q = (int*)malloc(graph->V * sizeof(int));
int front = 0, rear = 0;
visited[s] = true;
distance[s] = 0; // Distance from source to itself is 0
Q[rear++] = s;
while (front < rear) {
s = Q[front++];
for (int i = 0; i < graph->V; i++) {
if (graph->adj[s][i] && !visited[i]) {
visited[i] = true;
parent[i] = s;
distance[i] = distance[s] + 1;
Q[rear++] = i;
}
}
}
free(Q);
return distance[graph->V - 1];
}

int main() {
int m, n;
scanf("%d %d", &m, &n);
int r[m][n], d[m][n];
Graph* obj = createGraph(m * n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &r[i][j]);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &d[i][j]);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
for (int k = 1; k <= r[i][j]; k++) {
if (j + k < n)
addEdge(obj, i * n + j, i * n + j + k, 1); // Rightward edge
with weight 1
}
for (int k = 1; k <= d[i][j]; k++) {
if (i + k < m)
addEdge(obj, i * n + j, (i + k) * n + j, 1); // Downward edge
with weight 1
}
}
}
int result = BFS(obj);
printf("%d\n", result);
return 0;
}

You might also like