📌  相关文章
📜  替换指定的矩阵元素,使得没有两个相邻元素相等

📅  最后修改于: 2021-10-26 06:27:13             🧑  作者: Mango

给定维度为N * M矩阵arr[][] ,由‘O’‘F’ 组成,其中‘O’表示障碍物, ‘F’表示自由空间,任务是替换所有‘F’ s给定矩阵‘1’‘2’ ,这样没有两个相邻的单元格具有相同的值。

例子:

朴素方法:解决问题的最简单方法是使用回溯,类似于数独问题。但是,不是在给定位置放置N 个不同的值,而是需要将12放置在包含“F”的单元格上,这样没有两个相邻的元素彼此相等。请按照以下步骤解决问题:

  • 创建一个函数来检查矩阵中给定的位置是否有效。
  • 如果已到达矩阵的末尾,即i = N 和 j = M ,则返回True
  • 否则,如果当前索引是空闲空间,即arr[i][j]==’F’ ,则用‘1’‘2’填充索引。如果发现任何单元格无效,即它的任何相邻单元格具有相同的值,则打印“No”
  • 在矩阵的完全遍历之后,如果所有的’F’都被替换,使得相邻的矩阵元素都不相同,则打印“Yes”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if current
// position is safe or not
bool issafe(vector >& v, int i,
            int j, int n, int m, char ch)
{
    // Directions for adjacent cells
    int rowN[] = { 1, -1, 0, 0 };
    int colN[] = { 0, 0, 1, -1 };
 
    for (int k = 0; k < 4; k++) {
 
        // Check if any adjacent cell is same
        if (i + rowN[k] >= 0 && i + rowN[k] < n
            && j + colN[k] >= 0 && j + colN[k] < m
            && v[i + rowN[k]][j + colN[k]] == ch) {
            return false;
        }
    }
 
    // Current index is valid
    return true;
}
 
// Recursive function for backtracking
bool place(vector >& v,
           int n, int m)
{
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
 
            // Free cell
            if (v[i][j] == 'F') {
                break;
            }
        }
        if (j != m) {
            break;
        }
    }
 
    // All positions covered
    if (i == n && j == m) {
        return true;
    }
 
    // If position is valid for 1
    if (issafe(v, i, j, n, m, '1')) {
        v[i][j] = '1';
        if (place(v, n, m)) {
            return true;
        }
        v[i][j] = 'F';
    }
 
    // If position is valid for 2
    if (issafe(v, i, j, n, m, '2')) {
        v[i][j] = '2';
 
        // Recursive call for next
        // unoccupied position
        if (place(v, n, m)) {
            return true;
        }
 
        // If above conditions fails
        v[i][j] = 'F';
    }
    return false;
}
 
// Function to print valid matrix
void printMatrix(vector > arr,
                 int n, int m)
{
 
    place(arr, n, m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << arr[i][j];
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    // Given matrix
    vector > arr = {
        { 'F', 'F', 'F', 'F' },
        { 'F', 'O', 'F', 'F' },
        { 'F', 'F', 'O', 'F' },
        { 'F', 'F', 'F', 'F' },
    };
 
    // Give dimensions
    int n = 4, m = 4;
 
    // Function call
    printMatrix(arr, n, m);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG {
    public static boolean issafe(char v[][], int i,
            int j, int n, int m, char ch)
    {
        // Directions for adjacent cells
        int rowN[] = { 1, -1, 0, 0 };
        int colN[] = { 0, 0, 1, -1 };
 
        for (int k = 0; k < 4; k++) {
 
            // Check if any adjacent cell is same
            if (i + rowN[k] >= 0 && i + rowN[k] < n
                && j + colN[k] >= 0 && j + colN[k] < m
                && v[i + rowN[k]][j + colN[k]] == ch) {
                return false;
            }
        }
 
        // Current index is valid
        return true;
    }
 
    // Recursive function for backtracking
    public static boolean place(char v[][],
           int n, int m)
    {
        int i=0, j=0;
        for (i = 0; i < n; i++) {
            for (j = 0; j < m; j++) {
     
                // Free cell
                if (v[i][j] == 'F') {
                    break;
                }
            }
            if (j != m) {
                break;
            }
        }
 
        // All positions covered
        if (i == n && j == m) {
            return true;
        }
 
        // If position is valid for 1
        if (issafe(v, i, j, n, m, '1')) {
            v[i][j] = '1';
            if (place(v, n, m)) {
                return true;
            }
            v[i][j] = 'F';
        }
 
        // If position is valid for 2
        if (issafe(v, i, j, n, m, '2')) {
            v[i][j] = '2';
 
            // Recursive call for next
            // unoccupied position
            if (place(v, n, m)) {
                return true;
            }
 
            // If above conditions fails
            v[i][j] = 'F';
        }
        return false;
    }
    // Function to print valid matrix
    public static void printMatrix(char arr[][],
                 int n, int m)
    {
        place(arr, n, m);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }
   
    // Driver Code
    public static void main (String[] args) {
        char arr[][] = {
        { 'F', 'F', 'F', 'F' },
        { 'F', 'O', 'F', 'F' },
        { 'F', 'F', 'O', 'F' },
        { 'F', 'F', 'F', 'F' },
                            };
 
        // Give dimensions
        int n = 4, m = 4;
 
        // Function call
        printMatrix(arr, n, m);
    }
}


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if current
// position is safe or not   
public static bool issafe(char[,] v, int i,
                              int j, int n,
                              int m, char ch)
{
     
    // Directions for adjacent cells
    int[] rowN = { 1, -1, 0, 0 };
    int[] colN = { 0, 0, 1, -1 };
 
    for(int k = 0; k < 4; k++)
    {
         
        // Check if any adjacent cell is same
        if (i + rowN[k] >= 0 && i + rowN[k] < n &&
            j + colN[k] >= 0 && j + colN[k] < m &&
            v[(i + rowN[k]), (j + colN[k])] == ch)
        {
            return false;
        }
    }
 
    // Current index is valid
    return true;
}
 
// Recursive function for backtracking
public static bool place(char[,] v,
                         int n, int m)
{
    int i = 0, j = 0;
     
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
        {
             
            // Free cell
            if (v[i, j] == 'F')
            {
                break;
            }
        }
        if (j != m)
        {
            break;
        }
    }
 
    // All positions covered
    if (i == n && j == m)
    {
        return true;
    }
 
    // If position is valid for 1
    if (issafe(v, i, j, n, m, '1'))
    {
        v[i, j] = '1';
         
        if (place(v, n, m))
        {
            return true;
        }
        v[i, j] = 'F';
    }
 
    // If position is valid for 2
    if (issafe(v, i, j, n, m, '2'))
    {
        v[i, j] = '2';
 
        // Recursive call for next
        // unoccupied position
        if (place(v, n, m))
        {
            return true;
        }
 
        // If above conditions fails
        v[i, j] = 'F';
    }
    return false;
}
 
// Function to print valid matrix
public static void printMatrix(char[,] arr,
                               int n, int m)
{
    place(arr, n, m);
     
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            Console.Write(arr[i, j]);
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main()
{
    char[,] arr = { { 'F', 'F', 'F', 'F' },
                    { 'F', 'O', 'F', 'F' },
                    { 'F', 'F', 'O', 'F' },
                    { 'F', 'F', 'F', 'F' },};
 
    // Give dimensions
    int n = 4, m = 4;
 
    // Function call
    printMatrix(arr, n, m);
}
}
 
// This code is contributed by susmitakundugoaldanga


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to display the valid matrix
void print(vector > arr, int n, int m)
{
 
    // Traverse the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            char a = arr[i][j];
 
            // If the current cell is a free
            // space and is even-indexed
            if ((i + j) % 2 == 0 && a == 'F') {
                arr[i][j] = '1';
            }
            // If the current cell is a free
            // space and is odd-indexed
            else if (a == 'F') {
                arr[i][j] = '2';
            }
        }
    }
 
    // Print the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << arr[i][j];
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    // Given N and M
    int n = 4, m = 4;
 
    // Given matrix
    vector > arr = {
        { 'F', 'F', 'F', 'F' },
        { 'F', 'O', 'F', 'F' },
        { 'F', 'F', 'O', 'F' },
        { 'F', 'F', 'F', 'F' },
    };
 
    // Function call
    print(arr, n, m);
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG
{
    // Function to display the valid matrix
    public static void print(char arr[][], int n, int m)
    {
        // Traverse the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                char a = arr[i][j];
 
                // If the current cell is a free
                // space and is even-indexed
                if ((i + j) % 2 == 0 && a == 'F') {
                    arr[i][j] = '1';
                }
                // If the current cell is a free
                // space and is odd-indexed
                else if (a == 'F') {
                    arr[i][j] = '2';
                }
            }
        }
 
        // Print the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }
    
    // Driver Code
    public static void main (String[] args) {
        // Given N and M
        int n = 4, m = 4;
 
        // Given matrix
        char arr[][] = {
                        { 'F', 'F', 'F', 'F' },
                        { 'F', 'O', 'F', 'F' },
                        { 'F', 'F', 'O', 'F' },
                        { 'F', 'F', 'F', 'F' }};
 
        // Function call
        print(arr, n, m);
    }
}


Python3
# Python3 program for the above approach
 
# Function to display the valid matrix
def Print(arr, n, m):
 
    # Traverse the matrix
    for i in range(n):
        for j in range(m):
            a = arr[i][j]
 
            # If the current cell is a free
            # space and is even-indexed
            if ((i + j) % 2 == 0 and a == 'F') :
                arr[i][j] = '1'
             
            # If the current cell is a free
            # space and is odd-indexed
            elif (a == 'F') :
                arr[i][j] = '2'
 
    # Print the matrix
    for i in range(n) :
        for j in range(m) :
            print(arr[i][j], end = "")
     
        print()
 
# Given N and M
n, m = 4, 4
 
# Given matrix
arr = [
    [ 'F', 'F', 'F', 'F' ],
    [ 'F', 'O', 'F', 'F' ],
    [ 'F', 'F', 'O', 'F' ],
    [ 'F', 'F', 'F', 'F' ]]
 
# Function call
Print(arr, n, m)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to display the valid matrix
public static void print(char[,] arr, int n,
                                      int m)
{
     
    // Traverse the matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            char a = arr[i, j];
 
            // If the current cell is a free
            // space and is even-indexed
            if ((i + j) % 2 == 0 && a == 'F')
            {
                arr[i, j] = '1';
            }
             
            // If the current cell is a free
            // space and is odd-indexed
            else if (a == 'F')
            {
                arr[i, j] = '2';
            }
        }
    }
 
    // Print the matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            Console.Write(arr[i, j]);
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given N and M
    int n = 4, m = 4;
 
    // Given matrix
    char[,] arr = { { 'F', 'F', 'F', 'F' },
                    { 'F', 'O', 'F', 'F' },
                    { 'F', 'F', 'O', 'F' },
                    { 'F', 'F', 'F', 'F' }};
 
    // Function call
    print(arr, n, m);
}
}
 
// This code is contributed by sanjoy_62


Javascript


输出
1212
2O21
12O2
2121

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

高效方法:我们的想法是简单地通过1替代任何‘F’如果小区的奇偶性(I,J)1,即,第(i + j)的%21。否则,将‘F’替换为2 。请按照以下步骤解决问题:

  • 遍历给定的矩阵。
  • 对于遍历的每个单元格(i, j) ,如果单元格arr[i][j]等于‘F’并且(i + j) % 2等于1 ,则分配arr[i][j] = 1 。否则,分配arr[i][j] = 2

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to display the valid matrix
void print(vector > arr, int n, int m)
{
 
    // Traverse the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            char a = arr[i][j];
 
            // If the current cell is a free
            // space and is even-indexed
            if ((i + j) % 2 == 0 && a == 'F') {
                arr[i][j] = '1';
            }
            // If the current cell is a free
            // space and is odd-indexed
            else if (a == 'F') {
                arr[i][j] = '2';
            }
        }
    }
 
    // Print the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << arr[i][j];
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    // Given N and M
    int n = 4, m = 4;
 
    // Given matrix
    vector > arr = {
        { 'F', 'F', 'F', 'F' },
        { 'F', 'O', 'F', 'F' },
        { 'F', 'F', 'O', 'F' },
        { 'F', 'F', 'F', 'F' },
    };
 
    // Function call
    print(arr, n, m);
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
 
class GFG
{
    // Function to display the valid matrix
    public static void print(char arr[][], int n, int m)
    {
        // Traverse the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                char a = arr[i][j];
 
                // If the current cell is a free
                // space and is even-indexed
                if ((i + j) % 2 == 0 && a == 'F') {
                    arr[i][j] = '1';
                }
                // If the current cell is a free
                // space and is odd-indexed
                else if (a == 'F') {
                    arr[i][j] = '2';
                }
            }
        }
 
        // Print the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }
    
    // Driver Code
    public static void main (String[] args) {
        // Given N and M
        int n = 4, m = 4;
 
        // Given matrix
        char arr[][] = {
                        { 'F', 'F', 'F', 'F' },
                        { 'F', 'O', 'F', 'F' },
                        { 'F', 'F', 'O', 'F' },
                        { 'F', 'F', 'F', 'F' }};
 
        // Function call
        print(arr, n, m);
    }
}

蟒蛇3

# Python3 program for the above approach
 
# Function to display the valid matrix
def Print(arr, n, m):
 
    # Traverse the matrix
    for i in range(n):
        for j in range(m):
            a = arr[i][j]
 
            # If the current cell is a free
            # space and is even-indexed
            if ((i + j) % 2 == 0 and a == 'F') :
                arr[i][j] = '1'
             
            # If the current cell is a free
            # space and is odd-indexed
            elif (a == 'F') :
                arr[i][j] = '2'
 
    # Print the matrix
    for i in range(n) :
        for j in range(m) :
            print(arr[i][j], end = "")
     
        print()
 
# Given N and M
n, m = 4, 4
 
# Given matrix
arr = [
    [ 'F', 'F', 'F', 'F' ],
    [ 'F', 'O', 'F', 'F' ],
    [ 'F', 'F', 'O', 'F' ],
    [ 'F', 'F', 'F', 'F' ]]
 
# Function call
Print(arr, n, m)
 
# This code is contributed by divyeshrabadiya07

C#

// C# program for the above approach
using System;
 
class GFG{
     
// Function to display the valid matrix
public static void print(char[,] arr, int n,
                                      int m)
{
     
    // Traverse the matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            char a = arr[i, j];
 
            // If the current cell is a free
            // space and is even-indexed
            if ((i + j) % 2 == 0 && a == 'F')
            {
                arr[i, j] = '1';
            }
             
            // If the current cell is a free
            // space and is odd-indexed
            else if (a == 'F')
            {
                arr[i, j] = '2';
            }
        }
    }
 
    // Print the matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            Console.Write(arr[i, j]);
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given N and M
    int n = 4, m = 4;
 
    // Given matrix
    char[,] arr = { { 'F', 'F', 'F', 'F' },
                    { 'F', 'O', 'F', 'F' },
                    { 'F', 'F', 'O', 'F' },
                    { 'F', 'F', 'F', 'F' }};
 
    // Function call
    print(arr, n, m);
}
}
 
// This code is contributed by sanjoy_62

Javascript


输出
1212
2O21
12O2
2121

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

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