给定一个由N对整数组成的二维数组arr[][] ,使得每行中的两个元素表示它们是原始数组中的相邻元素。任务是使用给定的arr[]相邻元素对构造一个数组。
例子
Input: arr[] = {{5, 1 }, {3, 4 }, {3, 5}}
Output: 4 3 5 1
Explanation: The array can be constructed using the following operations:
Operation 1: The elements 4 and 1 have a single neighbor. Therefore, they can either be the first or last elements in the original array. Considering 4 to be the first element in the original array, A[] = {4}.
Operation 2: Place 3 adjacently to 4. Therefore, A[] = {4, 3}
Operation 3: Place 5 adjacently to 3. Therefore, A[] = {4, 3, 5}.
Operation 4: Place 1 as the last element in the array. Therefore, A[] = {4, 3, 5, 1}.
Input: arr[] = {{8, 11}, {-3, 6}, {-3, 8}}
Output: 6 -3 8 11
方法:可以使用Hashing和DFS来解决这个问题。请按照以下步骤解决问题:
- 使用 Map 初始化邻接列表,比如mp ,以存储分配给每个元素的相邻元素。
- 初始化一个向量,比如res ,以存储数组中的原始元素。
- 从角元素开始创建原始数组。因此,找到只有一个邻居的元素。这可以是原始数组的第一个或最后一个元素。
- 在res 中插入获取的元素。
- 遍历邻接表中的每个元素并检查其邻居是否被访问过。
- 在向量res 中插入未访问的邻居并遍历该元素的所有邻居。重复步骤 5,直到访问完所有元素。
- 返回资源。
下面是上述方法的实现:
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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live