#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
const int N = 10; 
bool Droga(int Lab[][N], int w, int k) {
    Lab[w][k] = 1;
    if (w == 0 || w == N - 1 || k == 0 || k == N - 1) { return true; }
    if (Lab[w - 1][k] == 0 && Droga(Lab, w - 1, k)) { return true; }
    if (Lab[w + 1][k] == 0 && Droga(Lab, w + 1, k)) { return true; }
    if (Lab[w][k - 1] == 0 && Droga(Lab, w, k - 1)) {return true; }
    if (Lab[w][k + 1] == 0 && Droga(Lab, w, k + 1)) { return true; }
    return false;
}
void WczytajLabirynt(int Lab[][N]){
    ifstream we("labirynt.txt");
    string s;
    if(!we) {
        cout << "Blad: Nie mozna otworzyc pliku!" << endl;
        return;
    }
    for (int i=0; i<N; i++){
        if (getline(we, s)) {
            for (int j=0; j<N; j++){
                if (j < s.length() && s[j] == 'X') Lab[i][j] = -1;
                else Lab[i][j] = 0;
            }
        }
    }
    we.close();
}

void WypiszLabirynt(int Lab[][N]){
    cout << "   ";
    for (int j=0; j<N; j++) cout << setw(3) << j;
    cout << endl;
    for (int i=0; i<N; i++){
        cout << setw(3) << i;
        for (int j=0; j<N; j++){
            if (Lab[i][j] == -1) cout << " X ";      // Sciana
            else if (Lab[i][j] == 1) cout << " . ";  // TRASA (to dopisalismy)
            else cout << "   ";                     // Puste pole
        }
        cout << endl;
    }
}

int main() {
    int Lab[N][N];
    WczytajLabirynt(Lab);
    int startW = 1; 
    int startK = 1;
    cout << "Labirynt przed startem:" << endl;
    WypiszLabirynt(Lab);
    cout << "\nUruchamiam algorytm z punktu (" << startW << ", " << startK << ")..." << endl;
    if (Lab[startW][startK] == -1) cout << "Blad: Punkt startowy to sciana!" << endl;
    else {
        if (Droga(Lab, startW, startK)) cout << "SUKCES: Znaleziono droge do krawedzi!" << endl;
        else cout << "PORAZKA: Nie znaleziono wyjscia." << endl;
    }
    cout << "\nStan labiryntu po szukaniu ( . to odwiedzone pola):" << endl;
    WypiszLabirynt(Lab);
    return 0;
}
