古典アルゴリズム迷宮問題1.単一パスDFS解C++実装

1867 ワード

/*
* File name  : maze_BFS.cpp
* Function   :          DFS   C++  
* Created on : 2016 5 12 
* Author     : [email protected]
* Copyright  :             ,            。
                     
*
  :    (1):          
0  ,1   

  
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 1 0 1 1 1 1 0 0
0 0 1 0 1 0 0 1 0 0
0 0 1 1 1 0 0 1 1 0
0 0 0 0 0 0 0 0 1 1
  

*
*/
#include <cstdio>
#include <iostream>

#pragma warning(disable:4996)

using namespace std;

typedef struct {
	int data;
	bool mark;
}Spot;

#define SIZE 10
Spot sarray[SIZE][SIZE];

typedef struct {
	int x;
	int y;
}Pos;
Pos store[SIZE * SIZE];
int store_pos = 0;
//int offset[4][2] = {-1,0,0,1,1,0,0,-1};

int offset[4][2] = { { -1,0 },
{ 0,1 },
{ 1,0 },
{ 0,-1 }
};


void DFS(Spot data[][SIZE], int x, int y);

int main(int argc, char** argv)
{
	int M = 0, N = 0;

	freopen("input.txt", "r", stdin);
	cin >> M >> N;

	for (int i = 0; i<M; i++)
		for (int j = 0; j < N; j++) {
			cin >> sarray[i][j].data;  // get input data
			sarray[i][j].mark = 0;
		}


	DFS(sarray, 0, 0);

	for (int i = 0; i < store_pos; i++) {
		cout << "( " << store[i].x << " , " << store[i].y << " )" << endl;
	}

	return 0;
}

void DFS(Spot data[][SIZE], int x, int y) {
	int tmpx, tmpy;

	data[x][y].mark = 1;
	store[store_pos].x = x;
	store[store_pos++].y = y;

	for (int k = 0; k < 4; k++) {
		tmpx = x + offset[k][0];
		tmpy = y + offset[k][1];
		if (tmpx >= 0 && tmpx < SIZE  // x    
			&&	tmpy >= 0 && tmpy < SIZE // y    
			&&  data[tmpx][tmpy].mark == 0//      
			&& data[tmpx][tmpy].data == 1
			) {
			DFS(data, tmpx, tmpy);
		}
	}

}