📌  相关文章
📜  检查是否存在从给定单元格到矩阵的任何边界元素且元素总和不超过 K 的路径

📅  最后修改于: 2021-09-07 02:07:41             🧑  作者: Mango

给定维度为M * N的矩阵grid[][] ,三个整数X, YK ,任务是检查是否存在从单元格(X, Y)到矩阵的任何边界单元格的任何路径,使得路径中存在的矩阵元素的总和最多为 K 。如果不存在这样的路径,则打印“No” 。否则,打印“是” 。任何单元格的可能移动是向上向下向左向右

例子:

方法:给定的问题可以通过使用回溯来解决给定的起始单元格的所有可能路径,并检查是否存在任何路径直到给定矩阵的边界单元格,其组成元素的总和等于K或不.

请按照以下步骤解决问题:

  • 定义一个递归函数,比如findPath(X, Y, K, board) ,以检查是否存在从起始单元格(X, Y)到任何边界元素的任何路径。
    • 基本情况:如果达到X < 0Y < 0X >= MY >= N ,则返回true
    • 现在,检查grid[X][Y] >= K是否。如果发现为真,则标记当前访问的单元格。将grid[X][Y]的值递减K ,然后访问未访问的相邻单元格,即递归调用findPath(X + 1, Y, K), findPath(X, Y + 1, K), findPath(X – 1, Y, K)findPath(X, Y – 1, K)
      • 如果上述任何递归调用返回true ,则从当前递归调用返回true
      • 否则,将当前单元格标记为未访问。
    • 如果以上条件都不满足,则从当前递归调用中返回false
  • 现在,如果函数findPath(X, Y, K)返回true,则打印“Yes” 。否则,打印“否”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if it is valid
// to move to the given index or not
bool isValid(vector >& board,
             int i, int j, int K)
{
    if (board[i][j] <= K) {
        return true;
    }
 
    // Otherwise return false
    return false;
}
 
// Function to check if there exists a
// path from the cell (X, Y) of the
// matrix to any boundary cell with
// sum of elements at most K or not
bool findPath(vector >& board,
              int X, int Y,
              int M, int N, int K)
{
 
    // Base Case
    if (X < 0 || X == M
        || Y < 0 || Y == N) {
        return true;
    }
 
    // If K >= board[X][Y]
    if (isValid(board, X, Y, K)) {
 
        // Stores the current element
        int board_XY = board[X][Y];
 
        // Mark the current cell as visited
        board[X][Y] = INT_MAX;
 
        // Visit all the adjacent cells
        if (findPath(board, X + 1, Y, M,
                     N, K - board_XY)
            || findPath(board, X - 1, Y, M,
                        N, K - board_XY)
            || findPath(board, X, Y + 1, M,
                        N, K - board_XY)
            || findPath(board, X, Y - 1, M,
                        N, K - board_XY)) {
            return true;
        }
 
        // Mark the cell unvisited
        board[X][Y] = board_XY;
    }
 
    // Return false
    return false;
}
 
// Driver Code
int main()
{
    vector > grid = {
        { 25, 5, 25, 25, 25, 25 },
        { 25, 1, 1, 5, 12, 25 },
        { 25, 1, 12, 0, 15, 25 },
        { 22, 1, 11, 2, 19, 15 },
        { 25, 2, 2, 1, 12, 15 },
        { 25, 9, 10, 1, 11, 25 },
        { 25, 25, 25, 25, 25, 25 }
    };
 
    int K = 17;
    int M = grid.size();
    int N = grid[0].size();
    int X = 2, Y = 3;
 
    if (findPath(grid, X, Y, M, N, K))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to check if it is valid
// to move to the given index or not
static boolean isValid(int[][] board, int i,
                       int j, int K)
{
    if (board[i][j] <= K)
    {
        return true;
    }
 
    // Otherwise return false
    return false;
}
 
// Function to check if there exists a
// path from the cell (X, Y) of the
// matrix to any boundary cell with
// sum of elements at most K or not
static boolean findPath(int[][] board, int X, int Y,
                        int M, int N, int K)
{
     
    // Base Case
    if (X < 0 || X == M || Y < 0 || Y == N)
    {
        return true;
    }
 
    // If K >= board[X][Y]
    if (isValid(board, X, Y, K))
    {
         
        // Stores the current element
        int board_XY = board[X][Y];
 
        // Mark the current cell as visited
        board[X][Y] = Integer.MAX_VALUE;
 
        // Visit all the adjacent cells
        if (findPath(board, X + 1, Y, M, N,
                            K - board_XY) ||
            findPath(board, X - 1, Y, M, N,
                            K - board_XY) ||
            findPath(board, X, Y + 1, M, N,
                               K - board_XY) ||
            findPath(board, X, Y - 1, M, N,
                               K - board_XY))
        {
            return true;
        }
 
        // Mark the cell unvisited
        board[X][Y] = board_XY;
    }
 
    // Return false
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int[][] grid = { { 25, 5, 25, 25, 25, 25 },
                     { 25, 1, 1, 5, 12, 25 },
                     { 25, 1, 12, 0, 15, 25 },
                     { 22, 1, 11, 2, 19, 15 },
                     { 25, 2, 2, 1, 12, 15 },
                     { 25, 9, 10, 1, 11, 25 },
                     { 25, 25, 25, 25, 25, 25 } };
 
    int K = 17;
    int M = grid.length;
    int N = grid[0].length;
    int X = 2, Y = 3;
 
    if (findPath(grid, X, Y, M, N, K))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by ukasp


Python3
# Python3 program for the above approach
import sys
 
INT_MAX = sys.maxsize
 
# Function to check if it is valid
# to move to the given index or not
def isValid(board, i, j, K):
 
    if (board[i][j] <= K):
        return True
 
    # Otherwise return false
    return False
 
# Function to check if there exists a
# path from the cell (X, Y) of the
# matrix to any boundary cell with
# sum of elements at most K or not
def findPath(board, X, Y, M, N, K):
 
    # Base Case
    if (X < 0 or X == M or
        Y < 0 or Y == N):
        return True
 
    # If K >= board[X][Y]
    if (isValid(board, X, Y, K)):
 
        # Stores the current element
        board_XY = board[X][Y]
 
        # Mark the current cell as visited
        board[X][Y] = INT_MAX
 
        # Visit all the adjacent cells
        if (findPath(board, X + 1, Y, M,
                     N, K - board_XY) or
            findPath(board, X - 1, Y, M,
                     N, K - board_XY) or
            findPath(board, X, Y + 1, M,
                     N, K - board_XY) or
            findPath(board, X, Y - 1, M,
                     N, K - board_XY)):
            return True;
     
        # Mark the cell unvisited
        board[X][Y] = board_XY
 
    # Return false
    return False
 
# Driver Code
if __name__ ==  "__main__":
     
    grid = [
        [ 25, 5, 25, 25, 25, 25 ],
        [ 25, 1, 1, 5, 12, 25 ],
        [ 25, 1, 12, 0, 15, 25 ],
        [ 22, 1, 11, 2, 19, 15 ],
        [ 25, 2, 2, 1, 12, 15 ],
        [ 25, 9, 10, 1, 11, 25 ],
        [ 25, 25, 25, 25, 25, 25 ] ]
 
    K = 17
    M = len(grid)
    N = len(grid[0])
    X = 2
    Y = 3
 
    if (findPath(grid, X, Y, M, N, K)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to check if it is valid
// to move to the given index or not
static bool isValid(int[,] board, int i,
                    int j, int K)
{
    if (board[i, j] <= K)
    {
        return true;
    }
 
    // Otherwise return false
    return false;
}
 
// Function to check if there exists a
// path from the cell (X, Y) of the
// matrix to any boundary cell with
// sum of elements at most K or not
static bool findPath(int[,] board, int X, int Y,
                     int M, int N, int K)
{
     
    // Base Case
    if (X < 0 || X == M ||
        Y < 0 || Y == N)
    {
        return true;
    }
 
    // If K >= board[X][Y]
    if (isValid(board, X, Y, K))
    {
         
        // Stores the current element
        int board_XY = board[X, Y];
 
        // Mark the current cell as visited
        board[X, Y] = int.MaxValue;
 
        // Visit all the adjacent cells
        if (findPath(board, X + 1, Y, M, N,
                            K - board_XY) ||
            findPath(board, X - 1, Y, M, N,
                            K - board_XY) ||
            findPath(board, X, Y + 1, M, N,
                               K - board_XY) ||
            findPath(board, X, Y - 1, M, N,
                               K - board_XY))
        {
            return true;
        }
 
        // Mark the cell unvisited
        board[X, Y] = board_XY;
    }
 
    // Return false
    return false;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[,] grid = { { 25, 5, 25, 25, 25, 25 },
                    { 25, 1, 1, 5, 12, 25 },
                    { 25, 1, 12, 0, 15, 25 },
                    { 22, 1, 11, 2, 19, 15 },
                    { 25, 2, 2, 1, 12, 15 },
                    { 25, 9, 10, 1, 11, 25 },
                    { 25, 25, 25, 25, 25, 25 } };
 
    int K = 17;
    int M = grid.Length;
    int N = grid.GetLength(0);
    int X = 2, Y = 3;
 
    if (findPath(grid, X, Y, M, N, K))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by AnkThon


Javascript


输出:
Yes

时间复杂度: O(3 N * M )
辅助空间: O(N * M)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live