ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자료구조...78
    일지 2021. 4. 20. 11:12

    ArrayGraph 삭제 메서드)

    노드와 에지를 삭제하는 메서드를 구현한다.

     

    ArrayGraph.cpp

    /// <summary>
    /// ArrayGraph에서 지정된 인덱스의 노드를 제거한다.
    /// </summary>
    /// <param name="value">제거할 값</param>
    void ArrayGraph::RemoveNode(int index)
    {
    	if (index < 0 || index >= m_nodeCount)
    	{
    		return;
    	}
    
    	for (int i = index; i < m_nodeCount - 1; i++)
    	{
    		for (int j = 0; j < m_nodeCount; j++)
    		{
    			m_graph[i][j] = m_graph[i + 1][j];
    		}
    
    		for (int j = 0; j < m_nodeCount; j++)
    		{
    			m_graph[j][i] = m_graph[j][i + 1];
    		}
    	}
    
    	for (int i = 0; i < m_nodeCount; i++)
    	{
    		m_graph[i][m_nodeCount - 1] = 0;
    		m_graph[m_nodeCount - 1][i] = 0;
    	}
    
    	m_nodeCount--;
    }
    
    /// <summary>
    /// ArrayGraph에서 from -> to 인 간선을 제거한다.
    /// </summary>
    /// <param name="from">시작 노드</param>
    /// <param name="to">끝 노드</param>
    void ArrayGraph::RemoveEdge(int from, int to)
    {
    	if (from < 0 || from >= m_nodeCount || to < 0 || to >= m_nodeCount)
    	{
    		return;
    	}
    
    	if (m_graph[from][to] > 0)
    	{
    		m_graph[from][to]--;
    	}
    }
    
    /// <summary>
    /// ArrayGraph의 모든 노드 및 간선을 제거한다.
    /// </summary>
    void ArrayGraph::Clear()
    {
    	m_nodeCount = 0;
    
    	for (size_t i = 0; i < m_nodeCapacity; i++)
    	{
    		std::fill_n(m_graph[i], m_nodeCapacity, 0);
    	}
    }

     

    main.cpp

    #include <iostream>
    #include "Graph/ArrayGraph.h"
    
    // 생성한 자료구조 테스트용 메인
    int main()
    {
    	ArrayGraph graph;
    
    	graph.InsertNode();
    	graph.InsertNode();
    	graph.InsertNode();
    	graph.InsertNode();
    
    	graph.InsertEdge(0, 1);
    	graph.InsertEdge(0, 3);
    	graph.InsertEdge(1, 1);
    	graph.InsertEdge(1, 2);
    	graph.InsertEdge(1, 3);
    	graph.InsertEdge(2, 0);
    	graph.InsertEdge(2, 3);
    	graph.InsertEdge(3, 0);
    	graph.PrintInfo();
    
    	graph.RemoveEdge(3, 0);
    	graph.PrintInfo();
    
    	graph.RemoveNode(1);
    	graph.PrintInfo();
    
    	graph.Clear();
    	graph.PrintInfo();
    }

     

    실행결과

    ----------------------
    Capacity: 5
    Count: 4
     0  1  0  1  0
     0  1  1  1  0
     1  0  0  1  0
     1  0  0  0  0
     0  0  0  0  0
    ----------------------
    
    ----------------------
    Capacity: 5
    Count: 4
     0  1  0  1  0
     0  1  1  1  0
     1  0  0  1  0
     0  0  0  0  0
     0  0  0  0  0
    ----------------------
    
    ----------------------
    Capacity: 5
    Count: 3
     0  0  1  0  0
     1  0  1  0  0
     0  0  0  0  0
     0  0  0  0  0
     0  0  0  0  0
    ----------------------
    
    ----------------------
    Capacity: 5
    Count: 0
     0  0  0  0  0
     0  0  0  0  0
     0  0  0  0  0
     0  0  0  0  0
     0  0  0  0  0
    ----------------------

    댓글

Designed by Tistory.