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

📅  最后修改于: 2021-04-17 15:54:24             🧑  作者: 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 。如果发现为真,则标记当前访问的单元格。将K减小grid [X] [Y]的值,然后访问未访问的相邻像元,即递归调用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


输出:
Yes

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