close
close
greedy algorthm in pyton 5x5

greedy algorthm in pyton 5x5

2 min read 24-01-2025
greedy algorthm in pyton 5x5

The greedy algorithm is a simple yet powerful approach to problem-solving. It makes the locally optimal choice at each stage, hoping to find a global optimum. While not guaranteed to find the absolute best solution in all cases, it often provides a good approximation efficiently. This article explores a practical application of a greedy algorithm using a 5x5 grid.

Understanding the Problem: Maximizing Value in a Grid

Imagine a 5x5 grid where each cell contains a numerical value representing a reward. Our goal is to find a path through the grid that maximizes the total reward collected, starting from the top-left corner and moving only down or right.

The Greedy Approach: Choosing the Best Immediate Reward

Our greedy algorithm will operate as follows:

  1. Start at the top-left corner.
  2. At each cell, examine the possible moves (down or right).
  3. Select the move that leads to the cell with the highest value.
  4. Repeat step 2 and 3 until the bottom-right corner is reached.

This strategy focuses on maximizing the immediate reward at every step, neglecting potential long-term consequences. Let's implement this in Python.

Python Implementation

import numpy as np

def greedy_grid_traversal(grid):
    """
    Finds a path through a grid using a greedy algorithm.

    Args:
        grid: A NumPy 2D array representing the grid.

    Returns:
        A tuple containing:
            - The total reward collected.
            - A list of coordinates representing the path taken.  
    """

    rows, cols = grid.shape
    path = [(0, 0)]  # Start at (0, 0)
    total_reward = grid[0, 0]
    current_row, current_col = 0, 0

    while current_row < rows - 1 or current_col < cols - 1:
        best_move = None
        best_reward = -1  # Initialize with a very low value

        # Explore possible moves (down and right)
        if current_row + 1 < rows:
            down_reward = grid[current_row + 1, current_col]
            if down_reward > best_reward:
                best_reward = down_reward
                best_move = (current_row + 1, current_col)
        if current_col + 1 < cols:
            right_reward = grid[current_row, current_col + 1]
            if right_reward > best_reward:
                best_reward = right_reward
                best_move = (current_row, current_col + 1)

        # Move to the cell with the highest reward
        current_row, current_col = best_move
        path.append(best_move)
        total_reward += best_reward

    return total_reward, path


# Example 5x5 grid
grid = np.array([
    [1, 3, 1, 5, 2],
    [4, 2, 8, 6, 9],
    [3, 1, 7, 4, 2],
    [5, 8, 2, 1, 3],
    [2, 4, 6, 9, 1]
])


total_reward, path = greedy_grid_traversal(grid)

print("Total reward:", total_reward)
print("Path:", path)

Output and Analysis

The output will show the total reward collected and the path taken. Remember, this is the path the greedy algorithm chose. A different algorithm might find a path with a higher total reward, but the greedy algorithm provides a reasonably good solution quickly.

Limitations of the Greedy Approach

The primary limitation of the greedy algorithm in this context (and many others) is its short-sightedness. It only considers the immediate best option, potentially missing a better overall solution further down the line. For more complex scenarios or when optimality is crucial, algorithms like dynamic programming might be more suitable.

Conclusion

This article demonstrated a simple yet effective application of the greedy algorithm for pathfinding in a 5x5 grid. The Python code provides a clear and concise implementation. Understanding the strengths and limitations of the greedy approach is key to applying it appropriately in various problem-solving scenarios.

Related Posts