0% found this document useful (0 votes)
6 views1 page

AI in Video Games (DFS)

The document contains a C++ implementation of a depth-first search (DFS) algorithm to find a path in a 2D grid from the top-left corner to the bottom-right corner. It checks for valid moves in four directions and marks visited cells to avoid cycles. The program outputs whether a winning path exists based on the grid configuration.

Uploaded by

dakiadmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

AI in Video Games (DFS)

The document contains a C++ implementation of a depth-first search (DFS) algorithm to find a path in a 2D grid from the top-left corner to the bottom-right corner. It checks for valid moves in four directions and marks visited cells to avoid cycles. The program outputs whether a winning path exists based on the grid configuration.

Uploaded by

dakiadmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

5.

AI in Video Games (DFS)

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

bool dfs(vector<vector<int>>& board, int x, int y, int goalX, int goalY,


vector<vector<bool>>& visited) {
if (x == goalX && y == goalY) return true;
visited[x][y] = true;

int dx[] = {-1, 1, 0, 0}; // up, down, left, right


int dy[] = {0, 0, -1, 1};

for (int dir = 0; dir < 4; dir++) {


int newX = x + dx[dir];
int newY = y + dy[dir];
if (newX >= 0 && newX < board.size() && newY >= 0 && newY < board[0].size()
&&
!visited[newX][newY] && board[newX][newY] == 0) {
if (dfs(board, newX, newY, goalX, goalY, visited))
return true;
}
}
return false;
}

int main() {
vector<vector<int>> board = {
{0, 0, 1},
{1, 0, 0},
{1, 1, 0}
};
int n = board.size(), m = board[0].size();
vector<vector<bool>> visited(n, vector<bool>(m, false));

if (dfs(board, 0, 0, n-1, m-1, visited))


cout << "Winning path found!\n";
else
cout << "No winning path.\n";
}

Output:-

Winning path found!

...Program finished with exit code 0


Press ENTER to exit console.

You might also like