Solution: Help the Policemen Catch the Thieves
This review provides a detailed analysis of the solution to the catching thieves problem.
We'll cover the following...
Solution #1: Brute Force
Press + to interact
int policeThief(char policeThiefArray[], int n, int k) {int result = 0;bool caught[n];for (int i = 0; i < n; i++) {caught[i] = false;}for (int i = 0; i < n; i++) {//check k steps forwardif (policeThiefArray[i] == 'P' && caught[i] == false) {for (int j = i; j < (j + k) && j < n && caught[i] == false; j++) {if (policeThiefArray[j] == 'T' && caught[j] == false) {caught[i] = true;caught[j] = true;break;}}}//check k steps backwardif (policeThiefArray[i] == 'P' && caught[i] == false) {for (int j = i; j > (j - k) && j > -1 && caught[i] == false; j--) {if (policeThiefArray[j] == 'T' && caught[j] == false) {caught[i] = true;caught[j] = true;break;}}}}for (int i = 0; i < n; i++) {if (policeThiefArray[i] == 'T' && caught[i] == true) {result++;}}return result;}int main() {int k, n;char policeTheifArray[] = {'P', 'T', 'T', 'P', 'T'};k = 2;n = sizeof(policeTheifArray) / sizeof(policeTheifArray[0]);cout << "Maximum thieves caught for {P, T, T, P, T}: " << policeThief(policeTheifArray, n, k) << endl;char policeTheifArray1[] = {'T', 'T', 'P', 'P', 'T', 'P'};k = 2;n = sizeof(policeTheifArray1) / sizeof(policeTheifArray1[0]);cout << "Maximum thieves caught for {T, T, P, P, T,P}: " << policeThief(policeTheifArray1, n, k) << endl;return 0;}
The brute force method takes the first police found and tries to match it with the nearest thief. However, you can see that this method is very lengthy, confusing, and time intensive.
Time Complexity
The time complexity is ...