hihocoder—二维字符数组匹配

华电北风吹
2016/3/6

题目描述:
hihocoder—1094 : Lost in the City
描述
Little Hi gets lost in the city. He does not know where he is. He does not know which direction is north.

Fortunately, Little Hi has a map of the city. The map can be considered as a grid of N*M blocks. Each block is numbered by a pair of integers. The block at the north-west corner is (1, 1) and the one at the south-east corner is (N, M). Each block is represented by a character, describing the construction on that block: ‘.’ for empty area, ‘P’ for parks, ‘H’ for houses, ‘S’ for streets, ‘M’ for malls, ‘G’ for government buildings, ‘T’ for trees and etc.

Given the blocks of 3*3 area that surrounding Little Hi(Little Hi is at the middle block of the 3*3 area), please find out the position of him. Note that Little Hi is disoriented, the upper side of the surrounding area may be actually north side, south side, east side or west side.

题目链接:
http://hihocoder.com/problemset/problem/1094

题目解析:
字符串匹配类问题跟预处理的好坏有很大的关系。可以采用求回文串中心扩展的思路,先对中心字符串匹配,然后环上匹配。

参考代码:

#include <iostream>
using namespace std;

#define MaxLength 200
char map[MaxLength][MaxLength];
char pattern[3][4];
char pList[8];

bool Match(int i, int j)
{
    char* list = new char[8]();

    list[0] = map[i - 1 + 0][j - 1 + 0];
    list[1] = map[i - 1 + 0][j - 1 + 1];
    list[2] = map[i - 1 + 0][j - 1 + 2];
    list[3] = map[i - 1 + 1][j - 1 + 2];
    list[4] = map[i - 1 + 2][j - 1 + 2];
    list[5] = map[i - 1 + 2][j - 1 + 1];
    list[6] = map[i - 1 + 2][j - 1 + 0];
    list[7] = map[i - 1 + 1][j - 1 + 0];

    for (int k = 0; k < 7; k += 2)
    {
        if (list[k] == pList[0])
        {
            int j = 1;
            while ((j < 8) && (list[(k + j) % 8] == pList[j]))
                j++;
            if (j == 8)
                return true;
        }
    }
    return false;
}

int main()
{
    int m, n;
    cin >> m >> n;
    for (int i = 0; i < m; i++)
    {
        cin >> map[i];
    }
    for (int i = 0; i < 3; i++)
    {
        cin >> pattern[i];
    }
    pList[0] = pattern[0][0];
    pList[1] = pattern[0][1];
    pList[2] = pattern[0][2];
    pList[3] = pattern[1][2];
    pList[4] = pattern[2][2];
    pList[5] = pattern[2][1];
    pList[6] = pattern[2][0];
    pList[7] = pattern[1][0];

    for (int i = 1; i < m - 1; i++)
    {
        for (int j = 1; j < n - 1; j++)
        {
            if (map[i][j] == pattern[1][1])
            {
                if (Match(i, j))
                {
                    cout << i + 1 <<" "<< j + 1 << endl;
                }
            }
        }
    }
    return 0;
}

你可能感兴趣的:(hihocoder—二维字符数组匹配)