打印从源点到矩阵所有 4 个角的所有路径
给定一个大小为M*N的二维数组arr[][] ,包含1和0 ,其中1表示可以访问该单元格,而0表示该单元格被阻塞。有一个源点(x, y) ,任务是打印从给定源到数组(0, 0), (0, N – 1), (M – 1)四个角中任意一个的所有路径, 0)和(M – 1, N – 1) 。
例子:
Input: arr[][] = {{1, 0, 0, 1, 0, 0, 1, 1}, {1, 1, 1, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {1, 0, 1, 0, 1, 0, 0, 1}, {0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 0, 0, 1, 1, 1, 1}, {1, 1, 0, 0, 0, 0, 0, 1} }. source = {4, 2}
Output : {“DRRUUURRUUR”, “DRRUUULLULLU”, “DRRDRRRD”, “DLDDL”}
Explanation : All the possible paths from the source to the 4 corners are
Input: arr[][] = {{0, 1, 0}, {0, 0, 0}, {0, 0, 0}}, source = {0, 1}
Output: No possible path
方法:这个想法是使用递归和回溯,通过考虑从源到目的地的每条可能路径来查找所有可能的路径,如果它是有效路径,则将其存储。请按照以下步骤解决问题:
- 初始化一个字符串向量ans[]来存储答案。
- 递归调用该函数以检查 4 个方向中的每一个,同时推动当前方向并使单元格被访问。
- 如果指针越过边界或者要访问的单元格不是有效单元格,即其值为0 ,则返回。
- 否则,存储当前单元格并到达任何一端,然后将其作为结果之一。
- 执行上述步骤后,打印数组ans[] 。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
struct direction {
int x, y;
char c;
};
// Function to check if we reached on
// of the entry/exit (corner) point.
bool isCorner(int i, int j, int M, int N)
{
if ((i == 0 && j == 0)
|| (i == 0 && j == N - 1)
|| (i == M - 1 && j == N - 1)
|| (i == M - 1 && j == 0))
return true;
return false;
}
// Function to check if the index is
// within the matrix boundary.
bool isValid(int i, int j, int M, int N)
{
if (i < 0 || i >= M || j < 0 || j >= N)
return false;
return true;
}
// Recursive helper function
void solve(int i, int j, int M, int N,
direction dir[],
vector >& maze,
string& t, vector& ans)
{
// If any corner is reached push the
// string t into ans and return
if (isCorner(i, j, M, N)) {
ans.push_back(t);
return;
}
// For all the four directions
for (int k = 0; k < 4; k++) {
// The new ith index
int x = i + dir[k].x;
// The new jth index
int y = j + dir[k].y;
// The direction R/L/U/D
char c = dir[k].c;
// If the new cell is within the
// matrix boundary and it is not
// previously visited in same path
if (isValid(x, y, M, N)
&& maze[x][y] == 1) {
// Mark the new cell as visited
maze[x][y] = 0;
// Store the direction
t.push_back(c);
// Recur
solve(x, y, M, N, dir,
maze, t, ans);
// Backtrack to explore
// other paths
t.pop_back();
maze[x][y] = 1;
}
}
return;
}
// Function to find all possible paths
vector possiblePaths(
vector src, vector >& maze)
{
// Create a direction array for all
// the four directions
direction dir[4] = { { -1, 0, 'U' },
{ 0, 1, 'R' },
{ 1, 0, 'D' },
{ 0, -1, 'L' } };
// Stores the result
string temp;
vector ans;
solve(src[0], src[1], maze.size(),
maze[0].size(), dir,
maze, temp, ans);
return ans;
}
// Driver Code
int main()
{
// Initializing the variables
vector > maze = {
{ 1, 0, 0, 1, 0, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0 },
{ 1, 0, 1, 0, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 1, 0, 0, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 0, 0, 0, 1 },
};
vector src = { 4, 2 };
// Function Call
vector paths
= possiblePaths(src, maze);
// Print the result
if (paths.size() == 0) {
cout << "No Possible Paths";
return 0;
}
for (int i = 0; i < paths.size(); i++)
cout << paths[i] << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG {
static class direction {
int x, y;
char c;
direction(int x, int y, char c)
{
this.c = c;
this.x = x;
this.y = y;
}
};
// Function to check if we reached on
// of the entry/exit (corner) point.
static boolean isCorner(int i, int j, int M, int N)
{
if ((i == 0 && j == 0) || (i == 0 && j == N - 1)
|| (i == M - 1 && j == N - 1)
|| (i == M - 1 && j == 0))
return true;
return false;
}
// Function to check if the index is
// within the matrix boundary.
static boolean isValid(int i, int j, int M, int N)
{
if (i < 0 || i >= M || j < 0 || j >= N)
return false;
return true;
}
// Recursive helper function
static void solve(int i, int j, int M, int N,
direction dir[], int[][] maze,
String t, ArrayList ans)
{
// If any corner is reached push the
// string t into ans and return
if (isCorner(i, j, M, N)) {
ans.add(t);
return;
}
// For all the four directions
for (int k = 0; k < 4; k++) {
// The new ith index
int x = i + dir[k].x;
// The new jth index
int y = j + dir[k].y;
// The direction R/L/U/D
char c = dir[k].c;
// If the new cell is within the
// matrix boundary and it is not
// previously visited in same path
if (isValid(x, y, M, N) && maze[x][y] == 1) {
// Mark the new cell as visited
maze[x][y] = 0;
// Store the direction
t += c;
// Recur
solve(x, y, M, N, dir, maze, t, ans);
// Backtrack to explore
// other paths
t = t.substring(0, t.length() - 1);
maze[x][y] = 1;
}
}
return;
}
// Function to find all possible paths
static ArrayList possiblePaths(int[] src,
int[][] maze)
{
// Create a direction array for all
// the four directions
direction[] dir = { new direction(-1, 0, 'U'),
new direction(0, 1, 'R'),
new direction(1, 0, 'D'),
new direction(0, -1, 'L') };
// Stores the result
String temp = "";
ArrayList ans = new ArrayList<>();
solve(src[0], src[1], maze.length, maze[0].length,
dir, maze, temp, ans);
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Initializing the variables
int[][] maze = {
{ 1, 0, 0, 1, 0, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0 },
{ 1, 0, 1, 0, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 1, 0, 0, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 0, 0, 0, 1 },
};
int[] src = { 4, 2 };
// Function Call
ArrayList paths = possiblePaths(src, maze);
// Print the result
if (paths.size() == 0) {
System.out.println("No Possible Paths");
return;
}
for (int i = 0; i < paths.size(); i++) {
System.out.println(paths.get(i));
}
}
}
// This code is contributed by Karandeep1234
Python3
# Python program for the above approach
# Function to check if we reached on
# of the entry/exit (corner) point.
def isCorner(i, j, M, N):
if((i == 0 and j == 0) or (i == 0 and j == N-1) or (i == M-1 and j == N-1) or (i == M-1 and j == 0)):
return True
return False
# Function to check if the index is
# within the matrix boundary.
def isValid(i, j, M, N):
if(i < 0 or i >= M or j < 0 or j >= N):
return False
return True
# Recursive helper function
def solve(i, j, M, N, Dir, maze, t, ans):
# If any corner is reached push the
# string t into ans and return
if(isCorner(i, j, M, N)):
ans.append(t)
return
# For all the four directions
for k in range(4):
# The new ith index
x = i + Dir[k][0]
# The new jth index
y = j + Dir[k][1]
# The direction R/L/U/D
c = Dir[k][2]
# If the new cell is within the
# matrix boundary and it is not
# previously visited in same path
if(isValid(x, y, M, N) and maze[x][y] == 1):
# mark the new cell visited
maze[x][y] = 0
# Store the direction
t += c
solve(x, y, M, N, Dir, maze, t, ans)
# Backtrack to explore
# other paths
t = t[: len(t)-1]
maze[x][y] = 1
return
# Function to find all possible paths
def possiblePaths(src, maze):
# Create a direction array for all
# the four directions
Dir = [[-1, 0, 'U'], [0, 1, 'R'], [1, 0, 'D'], [0, -1, 'L']]
# stores the result
temp = ""
ans = []
solve(src[0], src[1], len(maze), len(maze[0]), Dir, maze, temp, ans)
return ans
# Driver code
# Initialise variable
maze = [[1, 0, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 1],
[0, 1, 1, 1, 1, 0, 0, 1],
[0, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 0, 0, 0, 0, 0, 1]]
src = [4, 2]
# function call
paths = possiblePaths(src, maze)
# Print the result
if(len(paths) == 0):
print("No Possible Paths")
else:
for i in paths:
print(i)
# This code is contributed by parthmanchanda81
Javascript
DRRUUURRUUR
DRRUUULLULLU
DRRDRRRD
DLDDL
时间复杂度: O(3 (M*N) )
辅助空间: O(3 (M*N) )