我正在为一个编程竞赛练习,对于每个问题,我都可以选择使用Python或C++,因此我可以使用任何最适合此问题的语言。 我卡在了http://progconz.elena.aut.ac.nz/attachments/article/74/10%20points%20Problem%20Set%202012.pdf上的问题F(“地图”)。基本上涉及在大型ASCII艺术品中匹配小型ASCII艺术品的出现。在C++中,我可以为每个ASCII艺术品制作一个向量。问题是如何匹配多行较小的部分。我不知道该怎么做。我不想让所有代码都为我编写,只需要了解解决问题所需的逻辑即可。谢谢任何帮助。这是我目前的进展:
#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main( int argc, char** argv )
{
int nScenarios, areaWidth, areaHeight, patternWidth, patternHeight;
cin >> nScenarios;
for( int a = 0; a < nScenarios; a++ )
{
//get the pattern info and make a vector
cin >> patternHeight >> patternWidth;
vector< vector< bool > > patternIsBuilding( patternHeight, vector<bool>( patternWidth, false ) );
//populate data
for( int i = 0; i < patternHeight; i++ )
{
string temp;
cin >> temp;
for( int j = 0; j < patternWidth; j++ )
{
patternIsBuilding.at( i ).at( j ) = ( temp[ j ] == 'X' );
}
}
//get the area info and make a vector
cin >> areaHeight >> areaWidth;
vector< vector< bool > > areaIsBuilding( areaHeight, vector<bool>( areaWidth, false ) );
//populate data
for( int i = 0; i < areaHeight; i++ )
{
string temp;
cin >> temp;
for( int j = 0; j < areaWidth; j++ )
{
areaIsBuilding.at( i ).at( j ) = ( temp[ j ] == 'X' );
}
}
//now the vectors contain a `true` for a building and a `false` for snow
//need to find the matches for patternIsBuilding inside areaIsBuilding
//how?
}
return 0;
}
编辑:从下面的评论中,我得到了Python的解决方案,来自J.F. Sebastian
。它可以工作,但我不完全理解它。我已经注释了我能够理解的部分,但需要帮助理解count_pattern
函数中的return
语句。
#function to read a matrix from stdin
def read_matrix():
#get the width and height for this matrix
nrows, ncols = map( int, raw_input().split() )
#get the matrix from input
matrix = [ raw_input() for _ in xrange( nrows ) ]
#make sure that it all matches up
assert all(len(row) == ncols for row in matrix)
#return the matrix
return matrix
#perform the check, given the pattern and area map
def count_pattern( pattern, area ):
#get the number of rows, and the number of columns in the first row (cause it's the same for all of them)
nrows = len( pattern )
ncols = len( pattern[0] )
#how does this work?
return sum(
pattern == [ row[ j:j + ncols ] for row in area[ i:i + nrows ] ]
for i in xrange( len( area ) - nrows + 1 )
for j in xrange( len( area[i] ) - ncols + 1 )
)
#get a number of scenarios, and that many times, operate on the two inputted matrices, pattern and area
for _ in xrange( int( raw_input() ) ):
print count_pattern( read_matrix(), read_matrix() )