给定矩阵的3个像元(X1,Y1) , (X2,Y2)和(X3,Y3)的坐标。任务是找到连接所有这三个单元的最小路径,并打印通过该路径连接的所有单元的计数。
注意:只能向上,向下,向左和向右移动。
例子:
Input: X1 = 0, Y1 = 0, X2 = 1, Y2 = 1, X3 = 2 and Y3 = 2
Output: 5
(0, 0), (1, 0), (1, 1), (1, 2), (2, 2) are the required cells.
Input: X1 = 0, Y1 = 0, X2 = 2, Y2 = 0, X3 = 1 and Y3 = 1
Output: 4
方法:首先将单元格从第一个具有最小行号的单元格排序到最后一个具有最大行号的单元格排序。另外,将这三个单元格中的最小列号和最大列号分别存储在变量MinCol和MaxCol中。
之后,将中间单元格(来自已排序单元格)的行号存储在变量MidRow中,并将此MidRow的所有单元格从MinCol标记为MaxCol 。
现在,我们的最后一步将是标记第一个和第三个单元格的所有列号,直到它们到达MidRow为止。
在这里,标记意味着我们将所需的单元格坐标存储在集合中。因此,我们的答案将是这个集合的大小。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum cells that are
// connected via the minimum length path
int Minimum_Cells(vector > v)
{
int col[3], i, j;
for (i = 0; i < 3; i++) {
int column_number = v[i].second;
// Array to store column number
// of the given cells
col[i] = column_number;
}
sort(col, col + 3);
// Sort cells in ascending
// order of row number
sort(v.begin(), v.end());
// Middle row number
int MidRow = v[1].first;
// Set pair to store required cells
set > s;
// Range of column number
int Maxcol = col[2], MinCol = col[0];
// Store all cells of middle row
// within column number range
for (i = MinCol; i <= Maxcol; i++) {
s.insert({ MidRow, i });
}
for (i = 0; i < 3; i++) {
if (v[i].first == MidRow)
continue;
// Final step to store all the column number
// of 1st and 3rd cell upto MidRow
for (j = min(v[i].first, MidRow);
j <= max(v[i].first, MidRow); j++) {
s.insert({ j, v[i].second });
}
}
return s.size();
}
// Driver Function
int main()
{
// vector pair to store X, Y, Z
vector > v = { { 0, 0 }, { 1, 1 }, { 2, 2 } };
cout << Minimum_Cells(v);
return 0;
}
Python3
# Python3 implementation of the approach
# Function to return the minimum cells that
# are connected via the minimum length path
def Minimum_Cells(v) :
col = [0] * 3
for i in range(3) :
column_number = v[i][1]
# Array to store column number
# of the given cells
col[i] = column_number
col.sort()
# Sort cells in ascending order
# of row number
v.sort()
# Middle row number
MidRow = v[1][0]
# Set pair to store required cells
s = set()
# Range of column number
Maxcol = col[2]
MinCol = col[0]
# Store all cells of middle row
# within column number range
for i in range(MinCol, int(Maxcol) + 1) :
s.add((MidRow, i))
for i in range(3) :
if (v[i][0] == MidRow) :
continue;
# Final step to store all the column
# number of 1st and 3rd cell upto MidRow
for j in range(min(v[i][0], MidRow),
max(v[i][0], MidRow) + 1) :
s.add((j, v[i][1]));
return len(s)
# Driver Code
if __name__ == "__main__" :
# vector pair to store X, Y, Z
v = [(0, 0 ), ( 1, 1 ), ( 2, 2 )]
print(Minimum_Cells(v))
# This code is contributed by Ryuga
输出:
5
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。