from fastapi import APIRouter, HTTPException from pydantic import BaseModel from typing import List, Optional, Dict, Any from problems.min_path_sum.problem import MinPathSumProblem router = APIRouter( prefix="/min_path_sum", tags=["min_path_sum"], responses={404: {"description": "Not found"}}, ) problem_solver = MinPathSumProblem() class GenerateRequest(BaseModel): rows: int = 5 cols: int = 5 min_val: int = 1 max_val: int = 20 class SolveRequest(BaseModel): grid: List[List[int]] algorithms: List[str] = ["dp", "recursion"] class BenchmarkRequest(BaseModel): sizes: List[int] = [4, 6, 8, 10, 12] # Assuming square grids for simplicity in benchmark input, or handle appropriately algorithms: List[str] = ["dp", "recursion"] @router.post("/generate") async def generate_case(req: GenerateRequest): return problem_solver.generate_case(rows=req.rows, cols=req.cols, min_val=req.min_val, max_val=req.max_val) @router.post("/solve") async def solve_case(req: SolveRequest): input_data = {"grid": req.grid} results = [] # Check dimensions for safety check if needed rows = len(req.grid) cols = len(req.grid[0]) if rows > 0 else 0 for algo in req.algorithms: try: # Recursion safety limit if algo == "recursion" and (rows + cols > 18): results.append({ "algorithm": algo, "error": "Input too large for Recursion (limit rows+cols <= 18)", "skipped": True }) continue res = problem_solver.solve(input_data, algo) results.append(res) except ValueError as e: results.append({"algorithm": algo, "error": str(e)}) return results @router.post("/benchmark") async def benchmark(req: BenchmarkRequest): benchmark_results = [] for size in req.sizes: # Use size as both rows and cols for benchmarking input_data = problem_solver.generate_case(rows=size, cols=size) size_result = {"size": size, "algorithms": []} for algo in req.algorithms: try: if algo == "recursion" and (size + size > 18): size_result["algorithms"].append({ "algorithm": algo, "time_seconds": None, "skipped": True }) continue res = problem_solver.solve(input_data, algo) size_result["algorithms"].append(res) except Exception as e: size_result["algorithms"].append({"algorithm": algo, "error": str(e)}) benchmark_results.append(size_result) return benchmark_results