challenge 文字列の八方向検索

与えられた矩形状の文字列中に存在する文字列"ウオリ"の位置を全て出力するプログラムを
書いてください。
文字列の検索方向は八方全てで、また連続している(左右や上下の境界をまたがない)ものを
対象とします。出力は起点"ウ"の座標と方向のリストにしてください。

サンプル入力:

リオウウリウ
ウオリウオリ
オリリオリウ
リリオオウオ

サンプル出力:

(2, 0), 左
(0, 1), 右
(0, 1), 下
(3, 1), 右
(4, 3), 左上

--
より一般には、任意の検索文字列への対応も考えてみてください。

Posted feedbacks - D

参考にしたページに「境界チェックに頼ったプログラムを書くべきではありません」と書いてあったにもかかわらず、それに頼ってしまっています。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import std.stdio;

class EightSearch {
private:
    wstring[] m_matrix;
    wstring m_keyword;

    struct Direction {
        int step_x;
        int step_y;
        wstring str;
    }

    static Direction[8] m_directions = [ 
            { step_x:1, step_y:0, str:"右" },
            { step_x:1, step_y:1, str:"右下" },
            { step_x:0, step_y:1, str:"下" },
            { step_x:-1, step_y:1, str:"左下" },
            { step_x:-1, step_y:0, str:"左" },
            { step_x:-1, step_y:-1, str:"左上" },
            { step_x:0, step_y:-1, str:"上" },
            { step_x:1, step_y:-1, str:"右上" } ];

    /* ある場所のある方向について探索 */
    void search_one(int start_y, int start_x, Direction d) {
        try {
            int tmp_x = start_x;
            int tmp_y = start_y;
            for (int i = 0; i < m_keyword.length; ++i) {
                if (m_keyword[i] != m_matrix[tmp_y][tmp_x]) {
                    return;
                }
                tmp_x += d.step_x;
                tmp_y += d.step_y;
            }

            /* 見つけた! */
            writefln("(%d, %d), %s", start_x, start_y, d.str);
        }
        catch (Exception) {
        }
    }

public:
    this(wstring[] m, wstring k) {
        m_matrix = m;
        m_keyword = k;
    }

    /* 全ての場所の全ての方向について探索 */
    void search_all() {
        for (int i = 0; i < m_matrix.length; ++i) {
            for (int j = 0; j < m_matrix[0].length; ++j) {
                if (m_keyword[0] != m_matrix[i][j]) {
                    continue;
                }
                foreach (k; m_directions) {
                    search_one(i, j, k);
                }
            }
        }
    }
}

/*
void main() {
    static wstring[] m = [
        "リオウウリウ",
        "ウオリウオリ",
        "オリリオリウ",
        "リリオオウオ"];
    static wstring k = "ウオリ";
    EightSearch es = new EightSearch(m, k);
    es.search_all();
}
*/

Index

Feed

Other

Link

Pathtraq

loading...