📜  二维数组上的深度优先遍历 (DFS)

📅  最后修改于: 2021-09-07 04:45:10             🧑  作者: Mango

给定一个维度为N * M的二维数组grid[][] ,任务是在给定的二维数组上执行深度 – 优先搜索遍历。

例子:

做法:思路是使用Stack Data Structure对二维数组进行DFS Traversal 。请按照以下步骤解决给定的问题:

  • 初始化一个堆栈,比如S,起始单元坐标为(0, 0)
  • 初始化一个维度为N * M的辅助布尔二维数组,所有值都为false ,用于标记访问过的单元格。
  • 声明一个函数isValid()来检查单元坐标是否有效,即位于给定矩阵的边界内并且是否未被访问。
  • 在堆栈不为空时进行迭代并执行以下步骤:
    • 弹出堆栈顶部的单元格并在该单元格打印元素。
    • 如果使用isValid()函数检查它们是否有效,则将与上面弹出的单元格相邻的单元格推入堆栈。

注意:方向向量用于以给定顺序遍历给定单元格的相邻单元格。例如, (x, y)是一个单元格,它的相邻单元格(x – 1, y), (x, y + 1), (x + 1, y), (x, y – 1)需要遍历,然后可以使用方向向量(-1, 0), (0, 1), (1, 0), (0, -1)按向上、向左、向下和向右的顺序来完成。

下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
using namespace std;
#define ROW 3
#define COL 3
 
// Initialize direction vectors
int dRow[] = { 0, 1, 0, -1 };
int dCol[] = { -1, 0, 1, 0 };
 
// Function to check if mat[row][col]
// is unvisited and lies within the
// boundary of the given matrix
bool isValid(bool vis[][COL],
             int row, int col)
{
    // If cell is out of bounds
    if (row < 0 || col < 0
        || row >= ROW || col >= COL)
        return false;
 
    // If the cell is already visited
    if (vis[row][col])
        return false;
 
    // Otherwise, it can be visited
    return true;
}
 
// Function to perform DFS
// Traversal on the matrix grid[]
void DFS(int row, int col,
         int grid[][COL],
         bool vis[][COL])
{
    // Initialize a stack of pairs and
    // push the starting cell into it
    stack > st;
    st.push({ row, col });
 
    // Iterate until the
    // stack is not empty
    while (!st.empty()) {
        // Pop the top pair
        pair curr = st.top();
        st.pop();
        int row = curr.first;
        int col = curr.second;
 
        // Check if the current popped
        // cell is a valid cell or not
        if (!isValid(vis, row, col))
            continue;
 
        // Mark the current
        // cell as visited
        vis[row][col] = true;
 
        // Print the element at
        // the current top cell
        cout << grid[row][col] << " ";
 
        // Push all the adjacent cells
        for (int i = 0; i < 4; i++) {
            int adjx = row + dRow[i];
            int adjy = col + dCol[i];
            st.push({ adjx, adjy });
        }
    }
}
 
// Driver Code
int main()
{
    int grid[ROW][COL] = { { -1, 2, 3 },
                           { 0, 9, 8 },
                           { 1, 0, 1 } };
 
    // Stores whether the current
    // cell is visited or not
    bool vis[ROW][COL];
    memset(vis, false, sizeof vis);
 
    // Function call
    DFS(0, 0, grid, vis);
 
    return 0;
}


Java
// Java program of the above approach
import java.util.Stack;
 
class GFG{
     
static int ROW = 3;
static int COL = 3;
 
// Intialize direction vectors
static int dRow[] = { 0, 1, 0, -1 };
static int dCol[] = { -1, 0, 1, 0 };
 
static class pair
{
    public int first;
    public int second;
 
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
static Boolean isValid(Boolean vis[][], int row,
                                        int col)
{
     
    // If cell is out of bounds
    if (row < 0 || col < 0 ||
        row >= ROW || col >= COL)
        return false;
 
    // If the cell is already visited
    if (vis[row][col])
        return false;
 
    // Otherwise, it can be visited
    return true;
}
 
// Function to perform DFS
// Traversal on the matrix grid[]
static void DFS(int row, int col, int grid[][],
                               Boolean vis[][])
{
     
    // Initialize a stack of pairs and
    // push the starting cell into it
    Stack st = new Stack();
    st.push(new pair(row, col));
 
    // Iterate until the
    // stack is not empty
    while (!st.empty())
    {
         
        // Pop the top pair
        pair curr = st.pop();
 
        row = curr.first;
        col = curr.second;
 
        // Check if the current popped
        // cell is a valid cell or not
        if (!isValid(vis, row, col))
            continue;
 
        // Mark the current
        // cell as visited
        vis[row][col] = true;
 
        // Print the element at
        // the current top cell
        System.out.print(grid[row][col] + " ");
 
        // Push all the adjacent cells
        for(int i = 0; i < 4; i++)
        {
            int adjx = row + dRow[i];
            int adjy = col + dCol[i];
            st.push(new pair(adjx, adjy));
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int grid[][] = { { -1, 2, 3 },
                     { 0, 9, 8 },
                     { 1, 0, 1 } };
                      
    Boolean vis[][] = new Boolean[ROW][COL];
    for(int i = 0; i < ROW; i++)
    {
        for(int j = 0; j < COL; j++)
        {
            vis[i][j] = false;
        }
    }
     
    // Function call
    DFS(0, 0, grid, vis);
}
}
 
// This code is contributed by abhinavjain194


Python3
# Python 3 program of the above approach
ROW = 3
COL = 3
 
# Initialize direction vectors
dRow = [0, 1, 0, -1]
dCol = [-1, 0, 1, 0]
vis = [[False for i in range(3)] for j in range(3)]
 
# Function to check if mat[row][col]
# is unvisited and lies within the
# boundary of the given matrix
def isValid(row, col):
    global ROW
    global COL
    global vis
     
    # If cell is out of bounds
    if (row < 0 or col < 0 or row >= ROW or col >= COL):
        return False
 
    # If the cell is already visited
    if (vis[row][col]):
        return False
 
    # Otherwise, it can be visited
    return True
 
# Function to perform DFS
# Traversal on the matrix grid[]
def DFS(row, col, grid):
    global dRow
    global dCol
    global vis
     
    # Initialize a stack of pairs and
    # push the starting cell into it
    st = []
    st.append([row, col])
 
    # Iterate until the
    # stack is not empty
    while (len(st) > 0):
        # Pop the top pair
        curr = st[len(st) - 1]
        st.remove(st[len(st) - 1])
        row = curr[0]
        col = curr[1]
 
        # Check if the current popped
        # cell is a valid cell or not
        if (isValid(row, col) == False):
            continue
 
        # Mark the current
        # cell as visited
        vis[row][col] = True
 
        # Print the element at
        # the current top cell
        print(grid[row][col], end = " ")
 
        # Push all the adjacent cells
        for i in range(4):
            adjx = row + dRow[i]
            adjy = col + dCol[i]
            st.append([adjx, adjy])
 
# Driver Code
if __name__ == '__main__':
    grid =  [[-1, 2, 3],
             [0, 9, 8],
             [1, 0, 1]]
 
    # Function call
    DFS(0, 0, grid)
     
    # This code is contributed by SURENDRA_GANGWAR.


Javascript


输出:
-1 2 3 8 1 0 9 0 1

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

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