Bootstrap

二维字符数组中字符串查找

首先输入一个数字N,接着输入N行字符,每个字符用逗号分隔,最终形成一个N * N的字符数组。然后再输入一个待查找的目标字符串,在上面字符数组中查找是否出现目标字符串,查找的规则是在起始位置 从左向右 或者 从上向下,每个单元格的字符只出现一次。如果查找成功,输出目标字符在字符数组总的(i,j)下标,用逗号分隔;如果查找失败,则输出字符串"N"。

例如:

输入:

4

A,C,C,F

C,D,E,D

B,E,S,S

F,E,C,A

ACCESS

输出:

0,0,0,1,0,2,1,2,2,2,2,3

本题使用回溯算法

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

vector<vector<int>> result;
string word;
vector<vector<char>> array;

bool findWord(int iStart, int jStart, int index, vector<vector<int>> r) {
    if (index >= word.size()) {
        result = r;
        return true;
    }

    for (int i = iStart; i < array.size(); i++) {
        for (int j = jStart; j < array[0].size(); j++) {
            if (array[i][j] == word[index]) {
                r.push_back(vector<int>{i, j});
                if (findWord(i + 1, j, index + 1, r) || findWord(i, j + 1, index + 1, r))
                    return true;
            } else {
                if (findWord(i + 1, j, index, r) || findWord(i, j + 1, index, r))
                    return true;
            }
        }
    }

    return false;
}

int main() {
    word.clear();
    array.clear();

    int N;

    if (cin >> N) {
        if (N <= 0) {
            cout << "N" << endl;
            return 0;
        }
        string line;
        getline(cin, line);
        while (N-- > 0 && getline(cin, line)) {
            vector<char> v;
            string s;
            stringstream ss(line);
            while (getline(ss, s, ',')) {
                v.push_back(s[0]);
            }
            array.push_back(v);
        }

    }

    if (cin >> word) {
        if (word.size() == 0) {
            cout << "N" << endl;
            return 0;
        }

        vector<vector<int>> r;
        if (findWord(0, 0, 0, r)) {
            for (int i = 0; i < result.size(); i++) {
                if (i < result.size() - 1) {
                    cout << result[i][0] << "," << result[i][1] << ",";
                } else {
                    cout << result[i][0] << "," << result[i][1];
                }
            }
            cout << endl;
        } else {
            cout << "N" << endl;
        }
    }

    return 0;
}

;