📜  使用 DFS 遍历打印矩阵元素

📅  最后修改于: 2021-10-25 05:16:44             🧑  作者: Mango

给定一个维度为M × N的整数矩阵grid[][] ,任务是使用 DFS 遍历打印矩阵元素。

例子:

递归方法:这个想法是使用递归深度优先搜索来遍历矩阵并打印其元素。请按照以下步骤解决问题:

  • 初始化一个 2D 布尔向量,比如vis[][] ,以跟踪已访问和未访问的索引。
  • 定义一个函数,比如isValid(i, j) ,以检查位置(i, j)是否有效,即(i, j)应该在矩阵内并且不被访问。
  • 定义一个递归函数DFS(i, j):
    • 在每次调用时,标记访问的当前位置(i, j)并在该位置打印元素。
    • 对所有相邻边进行递归调用,即DFS(i + 1, j), DFS(i, j + 1), DFS(i – 1, j)DFS(i, j – 1)如果各自的位置是有效即未访问且在矩阵内。
  • 最后调用函数DFS(0, 0)开始 DFS Traversal 打印矩阵。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Direction vectors
int dRow[] = { -1, 0, 1, 0 };
int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
bool isValid(vector >& vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
void DFSUtil(int row, int col,
             vector > grid,
             vector >& vis,
             int M, int N)
{
    // Mark the current cell visited
    vis[row][col] = true;
 
    // Print the element at the cell
    cout << grid[row][col] << " ";
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
 
// Function to print the matrix elements
void DFS(int row, int col,
         vector > grid,
         int M, int N)
{
    // Initialize a visiting matrix
    vector > vis(
        M + 1, vector(N + 1, false));
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
int main()
{
    // Given matrix
    vector > grid{ { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.size();
 
    // Column of the matrix
    int N = grid[0].size();
 
    DFS(0, 0, grid, M, N);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// Direction vectors
static int dRow[] = { -1, 0, 1, 0 };
static int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
static boolean isValid(boolean[][] vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
static void DFSUtil(int row, int col,
            int[][] grid,
            boolean[][] vis,
            int M, int N)
{
   
    // Mark the current cell visited
    vis[row][col] = true;
 
    // Print the element at the cell
    System.out.print(grid[row][col] + " ");
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
// Function to print the matrix elements
static void DFS(int row, int col,
        int[][] grid,
         int M, int N)
{
    // Initialize a visiting matrix
    boolean[][] vis = new boolean[M + 1][N + 1];
    for(int i = 0; i < M + 1; i++)
    {
        for(int j = 0; j < N + 1; j++)
        {
            vis[i][j] = false;
        }
    }
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
public static void main(String args[])
{
    // Given matrix
    int[][] grid = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.length;
 
    // Column of the matrix
    int N = grid[0].length;
 
    DFS(0, 0, grid, M, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.


Python3
# Python3 program for the above approach
 
# Direction vectors
dRow = [-1, 0, 1, 0]
dCol = [0, 1, 0, -1]
 
# Function to check if current
# position is valid or not
def isValid(row, col, COL, ROW):
    global vis
     
    # Check if the cell is out of bounds
    if (row < 0 or col < 0 or col > COL - 1 or row > ROW - 1):
        return False
 
    # Check if the cell is visited or not
    if (vis[row][col] == True):
        return False
    return True
 
# Utility function to prmatrix
# elements using DFS Traversal
def DFSUtil(row, col,grid, M, N):
    global vis
 
    # Mark the current cell visited
    vis[row][col] = True
 
    # Prthe element at the cell
    print(grid[row][col], end = " ")
 
    # Traverse all four adjacent
    # cells of the current element
    for i in range(4):
 
        x = row + dRow[i]
        y = col + dCol[i]
 
        # Check if x and y is
        # valid index or not
        if (isValid(x, y, M, N)):
            DFSUtil(x, y, grid, M, N)
 
# Function to prthe matrix elementsdef
def DFS(row, col,grid, M, N):
    global vis
    # Initialize a visiting matrix
 
    # Function call to prmatrix
    # elements by DFS traversal
    DFSUtil(0, 0, grid, M, N)
 
# Driver Code
if __name__ == '__main__':
     
    # Given matrix
    grid = [ [ 1, 2, 3, 4 ],
           [ 5, 6, 7, 8 ],
           [ 9, 10, 11, 12 ],
           [ 13, 14, 15, 16 ] ]
 
    # Row of the matrix
    M = len(grid)
 
    # Column of the matrix
    N = len(grid[0])
    vis = [[False for i in range(M)] for i in range(N)]
    DFS(0, 0, grid, M, N)
 
    # This code is contributed by mohit kumar 29.


C#
// C# program to implement
// the above approach
using System;
public class GFG
{
   
// Direction vectors
static int []dRow = { -1, 0, 1, 0 };
static int []dCol = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
static bool isValid(bool[,] vis,
             int row, int col,
             int COL, int ROW)
{
   
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row,col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
static void DFSUtil(int row, int col,
            int[,] grid,
            bool[,] vis,
            int M, int N)
{
   
    // Mark the current cell visited
    vis[row,col] = true;
 
    // Print the element at the cell
    Console.Write(grid[row,col] + " ");
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
   
// Function to print the matrix elements
static void DFS(int row, int col,
        int[,] grid,
         int M, int N)
{
   
    // Initialize a visiting matrix
    bool[,] vis = new bool[M + 1,N + 1];
    for(int i = 0; i < M + 1; i++)
    {
        for(int j = 0; j < N + 1; j++)
        {
            vis[i,j] = false;
        }
    }
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
public static void Main(String []args)
{
   
    // Given matrix
    int[,] grid = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.GetLength(0);
 
    // Column of the matrix
    int N = grid.GetLength(1);
    DFS(0, 0, grid, M, N);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Direction vectors
int dRow[] = { -1, 0, 1, 0 };
int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if curruent
// position is valid or not
bool isValid(vector >& vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out
    // of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Function to print the matrix elements
void DFS_iterative(vector > grid,
                   int M, int N)
{
 
    // Stores if a position in the
    // matrix been visited or not
    vector > vis(
        M + 5, vector(N + 5, false));
 
    // Initialize stack to implement DFS
    stack > st;
 
    // Push the first position of grid[][]
    // in the stack
    st.push({ 0, 0 });
 
    // Mark the cell (0, 0) visited
    vis[0][0] = true;
 
    while (!st.empty()) {
 
        // Stores top element of stack
        pair p = st.top();
 
        // Delete the top() element
        // of stack
        st.pop();
 
        int row = p.first;
        int col = p.second;
 
        // Print element at the cell
        cout << grid[row][col] << " ";
 
        // Traverse in all four adjacent
        // sides of current positions
        for (int i = 0; i < 4; i++) {
 
            int x = row + dRow[i];
            int y = col + dCol[i];
 
            // Check if x and y is valid
            // position and then push
            // the position of current
            // cell in the stack
            if (isValid(vis, x, y, M, N)) {
 
                // Push the current cell
                st.push({ x, y });
 
                // Mark current cell visited
                vis[x][y] = true;
            }
        }
    }
}
 
// Driver Code
int main()
{
    // Given matrix
    vector > grid{ { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.size();
 
    // Column of the matrix
    int N = grid[0].size();
 
    DFS_iterative(grid, M, N);
 
    return 0;
}


输出
1 2 3 4 8 12 16 15 11 7 6 10 14 13 9 5 

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

迭代方法:想法是使用迭代深度优先搜索遍历矩阵并打印矩阵元素。请按照以下步骤解决问题:

  • 定义一个函数,例如isValid(i, j) ,以检查位置(i, j)是否有效,即(i, j)位于矩阵内部且未被访问。
  • 初始化一个二维布尔向量,比如vis[][] ,用于跟踪一个位置,比如(i, j) ,它是否已经被访问过。
  • 初始化一个 stack> 说S来实现 DFS 遍历。
  • 首先将栈S 中的第一个单元格(0, 0)压入标记访问过的单元格。
  • 在堆栈S不为空时进行迭代:
    • 在每次迭代中,标记堆栈的顶部元素,例如(i, j)访问并打印该位置的元素并从堆栈S 中删除顶部元素。
    • 推相邻小区,即第(i + 1,j)的(I,J + 1),(I – 1,j)(I,J – 1)进栈如果各自的位置是有效的,即,没有访问过,并且矩阵内。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Direction vectors
int dRow[] = { -1, 0, 1, 0 };
int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if curruent
// position is valid or not
bool isValid(vector >& vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out
    // of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Function to print the matrix elements
void DFS_iterative(vector > grid,
                   int M, int N)
{
 
    // Stores if a position in the
    // matrix been visited or not
    vector > vis(
        M + 5, vector(N + 5, false));
 
    // Initialize stack to implement DFS
    stack > st;
 
    // Push the first position of grid[][]
    // in the stack
    st.push({ 0, 0 });
 
    // Mark the cell (0, 0) visited
    vis[0][0] = true;
 
    while (!st.empty()) {
 
        // Stores top element of stack
        pair p = st.top();
 
        // Delete the top() element
        // of stack
        st.pop();
 
        int row = p.first;
        int col = p.second;
 
        // Print element at the cell
        cout << grid[row][col] << " ";
 
        // Traverse in all four adjacent
        // sides of current positions
        for (int i = 0; i < 4; i++) {
 
            int x = row + dRow[i];
            int y = col + dCol[i];
 
            // Check if x and y is valid
            // position and then push
            // the position of current
            // cell in the stack
            if (isValid(vis, x, y, M, N)) {
 
                // Push the current cell
                st.push({ x, y });
 
                // Mark current cell visited
                vis[x][y] = true;
            }
        }
    }
}
 
// Driver Code
int main()
{
    // Given matrix
    vector > grid{ { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.size();
 
    // Column of the matrix
    int N = grid[0].size();
 
    DFS_iterative(grid, M, N);
 
    return 0;
}

输出:
1 5 9 13 14 15 16 12 8 7 3 4 11 10 6 2

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程