C++程序:查找下一起抢劫发生的地点
假设我们有一个大小为n x m的字符二维矩阵。其中存在两种字符 '*' 和 '.'。只有三个 '*',代表发生了3起抢劫,所有其他位置都标记为 '.'。侦探得到情报,第四起抢劫将发生在一个这样的单元格中:所有四个被抢劫的单元格构成一个矩形的顶点,且平行于地图的边。我们需要找到这个单元格。
问题类别
在数据结构中,数组是特定类型元素的有限集合。数组用于将相同类型的元素存储在连续的内存位置中。数组被赋予一个特定的名称,并在各种编程语言中通过该名称进行引用。要访问数组的元素,需要索引。我们使用术语“name[i]”来访问数组“name”中位置“i”处的特定元素。各种数据结构,如堆栈、队列、堆、优先队列,都可以使用数组实现。数组上的操作包括插入、删除、更新、遍历、搜索和排序操作。访问以下链接了解更多信息。此问题需要矩阵来存储输入,然后可以使用基于矩阵的操作来解决此问题。
https://tutorialspoint.com/data_structures_algorithms/array_data_structure.htm
https://tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm
因此,如果我们的问题的输入如下所示:
| * | . | * |
| * | . | . |
| . | . | . |
那么输出将是 (2, 3)
步骤
为了解决这个问题,我们将遵循以下步骤:
n := row count of matrix m := column count of matrix x := 0 y := 0 for initialize i := 0, when i < n, update (increase i by 1), do: for initialize j := 0, when j < m, update (increase j by 1), do: if matrix[i, j] is same as '*', then: x := x XOR i y := y XOR j print (x + 1, y + 1)
示例
让我们看看下面的实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
void solve(vector<vector<char>> matrix){
int n = matrix.size();
int m = matrix[0].size();
int x, y;
x = y = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
if (matrix[i][j] == '*'){
x ^= i;
y ^= j;
}
}
cout << x + 1 << ", " << y + 1 << endl;
}
int main(){
vector<vector<char>> matrix = { { '*', '.', '*' }, { '*', '.', '.' }, { '.', '.', '.' } };
solve(matrix);
}输入
{ { '*', '.', '*' }, { '*', '.', '.' }, { '.', '.', '.' } }输出
2, 3
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP