Skip to content

Instantly share code, notes, and snippets.

@splitline
Created June 16, 2017 23:30
Show Gist options
  • Save splitline/bf5a9f5dc465d649912e6aa01c301a9a to your computer and use it in GitHub Desktop.
Save splitline/bf5a9f5dc465d649912e6aa01c301a9a to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
using namespace std;
char grid[4][4];
bool used[4][4] = {0};
void clear(){//set all used array to false
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
used[i][j]=false;
}
bool recur(string str, int x, int y, int p) {
int direction[] = {1, 0, -1};
if (str[p] != grid[x][y]) return false;
else used[x][y] = true;
if (p == str.length() - 1 && str[p] == grid[x][y]) return true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int nextX = x + direction[i], nextY = y + direction[j];
if ((nextX < 4 && nextX >= 0) && (nextY < 4 && nextY >= 0) && !used[nextX][nextY] && recur(str, nextX, nextY, p + 1))
return true;
}
}
return false;
}
int main() {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
cin >> grid[i][j]; //input grid
ifstream fin("words.txt");
string str;
while (fin >> str) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
//find first char's position of str
if (grid[i][j] == str[0]) {
clear();
if (recur(str, i, j, 0)){//if recur result is true
cout << str << endl;
break;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment