📌  相关文章
📜  从给定的相邻元素对生成数组

📅  最后修改于: 2021-04-17 16:26:03             🧑  作者: Mango

给定一个二维数组arr [] [] ,该数组由N对整数组成,使得每行中的两个元素表示它们是原始数组中的相邻元素。任务是使用给定的arr []相邻元素对构造一个数组。

例子

方法:可以使用HashingDFS解决该问题。请按照以下步骤解决问题:

  1. 使用Map初始化一个邻接表,例如mp ,以存储分配给每个元素的相邻元素。
  2. 初始化一个向量,例如res ,以将原始元素存储在数组中。
  3. 从角元素开始创建原始数组。因此,找到只有一个邻居的元素。这可以是原始数组的第一个最后一个元素。
  4. 将获得的元素插入res
  5. 遍历邻接表中的每个元素,并检查是否访问了它的邻居。
  6. 在向量res中插入未访问的邻居,并遍历该元素的所有邻居。重复步骤5,直到访问了所有元素。
  7. 返回res

下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
using namespace std;
 
// Utility function to find original array
void find_original_array(vector >& A)
{
 
    // Map to store all neighbors for each element
    unordered_map > mp;
 
    // Vector to store original elements
    vector res;
 
    // Stotrs which array elements are visited
    unordered_map visited;
 
    // Adjacency list to store neighbors
    // of each array element
    for (auto& it : A) {
 
        mp[it.first].push_back(it.second);
        mp[it.second].push_back(it.first);
    }
 
    auto it = mp.begin();
 
    // Find the first corner element
    for (; it != mp.end(); it++) {
        if (it->second.size() == 1) {
            break;
        }
    }
 
    // Stores first element of
    // the original array
    int adjacent = it->first;
  
 
    // Push it into the original array
    res.push_back(it->first);
 
    // Mark as visted
    visited[it->first] = true;
 
    // Traversing the neighbors and check
    // if the elements are visited or not
    while (res.size() != A.size() + 1) {
 
        // Traverse adjacent elements
        for (auto& elements : mp[adjacent]) {
 
            // If element is not visited
            if (!visited[elements]) {
 
                // Push it into res
                res.push_back(elements);
 
                // Mark as visited
                visited[elements] = true;
 
                // Update the next adjacent
                adjacent = elements;
            }
        }
    }
 
    // Print original array
    for (auto it : res) {
        cout << it << " ";
    }
}
 
// Driver Code
int main()
{
 
    // Given pairs of adjacent elements
    vector > A
        = { { 5, 1 }, { 3, 4 }, { 3, 5 } };
 
    find_original_array(A);
    return 0;
}


Java
// Java program of the above approach
import java.io.*;
import java.util.*;
 
class Pair {
    int first, second;
    Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
class GFG {
    // Utility function to find original array
    static void find_original_array(List A)
    {
 
        // Map to store all neighbors for each element
        @SuppressWarnings("unchecked")
        Map > mp = new HashMap();
 
        // Vector to store original elements
        List res = new ArrayList();
 
        // Stotrs which array elements are visited
        @SuppressWarnings("unchecked")
        Map visited = new HashMap();
 
        // Adjacency list to store neighbors
        // of each array element
        for (Pair it : A) {
            List temp;
            temp = (mp.containsKey(it.first))
                       ? mp.get(it.first)
                       : new ArrayList();
            temp.add(it.second);
            mp.put(it.first, temp);
 
            temp = (mp.containsKey(it.second))
                       ? mp.get(it.second)
                       : new ArrayList();
            temp.add(it.first);
            mp.put(it.second, temp);
        }
 
        int it = 0;
 
        // Find the first corner element
        for (Map.Entry > entry :
             mp.entrySet()) {
            if (entry.getValue().size() == 1) {
                it = entry.getKey();
            }
        }
 
        // Stores first element of
        // the original array
        int adjacent = it;
 
        // Push it into the original array
        res.add(it);
 
        // Mark as visted
        visited.put(it, true);
 
        // Traversing the neighbors and check
        // if the elements are visited or not
        while (res.size() != A.size() + 1) {
 
            // Traverse adjacent elements
            for (int elements : mp.get(adjacent)) {
 
                // If element is not visited
                if (!visited.containsKey(elements)) {
 
                    // Push it into res
                    res.add(elements);
 
                    // Mark as visited
                    visited.put(elements, true);
 
                    // Update the next adjacent
                    adjacent = elements;
                }
            }
        }
 
        // Print original array
        for (int val : res) {
            System.out.print(val + " ");
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
        @SuppressWarnings("unchecked")
        List A = new ArrayList();
        A.add(new Pair(5, 1));
        A.add(new Pair(3, 4));
        A.add(new Pair(3, 5));
 
        find_original_array(A);
    }
}
 
// This code is contributed by jithin.


Python3
# Python3 program of the above approach
 
# Utility function to find original array
def find_original_array(A):
 
    # Map to store all neighbors for each element
    mp = [[] for i in range(6)]
 
    # Vector to store original elements
    res = []
 
    # Stotrs which array elements are visited
    visited = {}
 
    # A djacency list to store neighbors
    # of each array element
    for it in A:
        mp[it[0]].append(it[1])
        mp[it[1]].append(it[0])
 
    start = 0
 
    # Find the first corner element
    for it in range(6):
        if (len(mp[it]) == 1):
            start = it + 3
            break
 
    # Stores first element of
    # the original array  
    adjacent = start
 
    # Push it into the original array
    res.append(start)
 
    # Mark as visted
    visited[start] = True
 
    # Traversing the neighbors and check
    # if the elements are visited or not
    while (len(res) != len(A) + 1):
 
        # Traverse adjacent elements
        for elements in mp[adjacent]:
 
            # If element is not visited
            if (elements not in visited):
 
                # Push it into res
                res.append(elements)
 
                # Mark as visited
                visited[elements] = True
 
                # Update the next adjacent
                adjacent = elements
 
    # Print original array
    print(*res)
 
# Driver Code
if __name__ == '__main__':
 
    # Given pairs of adjacent elements
    A = [[5, 1],[ 3, 4],[ 3, 5]]
 
    find_original_array(A)
 
# This code is contributed by mohit kumar 29.


C#
// C# program of the above approach
using System;
using System.Collections.Generic;
 
public class Pair
{
  public int first, second;
  public Pair(int first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
 
public class GFG
{
 
  // Utility function to find original array
  static void find_original_array(List A)
  {
 
    // Map to store all neighbors for each element
    Dictionary> mp = new Dictionary>();
 
    // Vector to store original elements
    List res = new List();
 
    // Stotrs which array elements are visited
    Dictionary visited = new Dictionary();
 
    // Adjacency list to store neighbors
    // of each array element
    foreach (Pair it in A)
    {
      List temp;
      temp = (mp.ContainsKey(it.first))
        ? mp[it.first]
        : new List();
 
      temp.Add(it.second);
      if(!mp.ContainsKey(it.first))
        mp.Add(it.first, temp);
      else
        mp[it.first] = temp;
 
      temp = (mp.ContainsKey(it.second))
        ? mp[it.second]
        : new List();
      temp.Add(it.first);
      if(!mp.ContainsKey(it.second))
        mp.Add(it.second, temp);
      else
        mp[it.second] = temp;
 
 
    }
 
    int It = 0;
 
    // Find the first corner element
    foreach (int key in mp.Keys)
    {
      if(mp[key].Count == 1)
      {
        It=key;
      }
    }
 
    // Stores first element of
    // the original array
    int adjacent = It;
 
    // Push it into the original array
    res.Add(It);
 
    // Mark as visted
    visited.Add(It, true);
 
    // Traversing the neighbors and check
    // if the elements are visited or not
    while (res.Count != A.Count + 1)
    {
 
      // Traverse adjacent elements
      foreach (int elements in mp[adjacent])
      {
 
        // If element is not visited
        if (!visited.ContainsKey(elements))
        {
 
          // Push it into res
          res.Add(elements);
 
          // Mark as visited
          visited.Add(elements, true);
 
          // Update the next adjacent
          adjacent = elements;
        }
      }
    }
 
    // Print original array
    foreach (int val in res)
    {
      Console.Write(val + " ");
    }
  }
 
  // Driver Code
  static public void Main (){
    List A = new List();
    A.Add(new Pair(5, 1));
    A.Add(new Pair(3, 4));
    A.Add(new Pair(3, 5));
 
    find_original_array(A);
  }
}
 
// This code is contributed by avanitrachhadiya2155


输出:
4 3 5 1

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