【发布时间】:2019-09-04 10:24:44
【问题描述】:
给你一个字符矩阵。该矩阵有 N 行和 M 列。给定一个字符串 s,您必须判断是否可以从给定矩阵生成该字符串。 从矩阵生成字符串的规则是:
您必须从第 1 行中选择字符串的第一个字符,从第 2 行中选择第二个字符,依此类推。字符串的第 N+1 个字符将从第 1 行中选取,即可以循环遍历各行(第 1 行在第 N 行之后)。 如果从一行中选取某个字符的出现,则不能从该行中再次选取相同的出现。 如果可以使用给定规则从矩阵生成给定字符串,则必须打印 Yes,否则打印 No。
输入格式:
第一行由 T 组成,表示测试用例的数量。 每个测试用例包括: 第一行由两个整数 N 和 M 组成,表示矩阵维数。 接下来的 N 行每行包含 M 个字符。 最后一行包含一个字符串 s。
输出格式: 对于每个测试用例,如果可以生成字符串,则打印“是”,否则打印“否”。每个测试用例的答案应换行。
示例输入 1 3 3 阿坝 xyz bdr axbaydb
样本输出 是的
我们从第 1 行中选择“a”。现在,我们只能从第 1 行中再选择一个“a”,因为已经使用了一个“a”。 同样,“x”来自第 2 行,“b”来自第 3 行。 现在,我们再次回到第 1 行。 我们从第 1 行中选择“a”,从第 2 行中选择“y”,依此类推。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int testcase, row, col, x = 0, i = 0;
bool flag = true;
string word;
cin >> testcase; //number of testcases
for (int i = 0; i < testcase; i++)
{
cin >> row; //number of rows
cin >> col; //number of columns
char** arr = (char**)malloc(row * sizeof(char *)); //allocating memory for arr pointer to pointer based on the number of rows
for (int i = 0; i < row; i++)
{
arr[i] = (char*)malloc(col * sizeof(char)); //allocating memory for arr pointer
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> arr[i][j];
}
}
cin>>word;
while (x < word.length()) // looping through the given string until it reaches the end of the string
{
while (i <= row) // looping through the rows of the 2darray
{
for (int j = 0; j < col; j++) //looping through each element in 1d array
{
if (i == row) //to ensure that after the last row it goes back again to the first row and starts iterating from the first row
{
i = 0;
}
if (word[x] == arr[i][j]) // if character from the string matches the element in the 1st row of 2d array, we will go to the next character of the string and also go to the next row for searching the character in that row.
{
x++;
i++;
}
else
{
flag = false; // if the value is not found, we will set the flag to false
}
}
}
}
if (flag == false)
{
cout << "No"<<endl;
}
else
{
cout << "Yes"<<endl;
}
}
return 0;
}
以下代码未按预期工作
1
5 8
wxyqkbtk
xpbzexmh
ffkgmqnj
lfyrrwsn
vqfftarq
tswsgdzlpfxithvahmrffgax
【问题讨论】:
-
请将 cmets 添加到您的代码中,以显示您期望在每个分支上发生的情况(对于语句、退出条件以及 while 语句和退出条件。)。您可以使用调试器吗?
-
也就是说,请使用橡皮鸭法。您要求 SO 社区成为您的rubber duck。我们是相当愚蠢的橡皮鸭。请解释(通过 cmets)你的算法和每一行代码,就像对你的rubber duck 说话一样。这将帮助您成为更好的程序员,也将帮助我们帮助您。
-
对此我感到非常抱歉。我现在会更新它。
-
一旦找到匹配项,您就不会跳出列循环,这意味着您每次提高行号时都不会从头开始寻找匹配项。此外,一旦您遇到错误并返回 no,您可能应该停止查找。
-
该测试用例的预期输出应该是“否”,因为
s(测试用例字符串的第二个字符)不在第二行字母xpbzexmh内,对吧?
标签: c++ arrays data-structures dynamic-memory-allocation