POJ 1154 Letter game (DFS)

#include <stdio.h>

#define MAX 22

int rows;
int columns;
char board[MAX][MAX];
                   //up    down   left   right
int dirs[4][2] = {-1, 0,  1, 0,  0, -1,  0, 1};
int visitedLetters[26];
int maxMoves;

void DFS(int row, int column, int moves){
    int dir;
    for (dir = 0; dir < 4; dir++){
        int nextRow = row + dirs[dir][0];
        int nextCol = column + dirs[dir][1];
        int letter = board[nextRow][nextCol] - 'A';
        if (nextRow < 0 || nextRow == rows || nextCol < 0 || nextCol == columns
            || visitedLetters[letter]){
            continue;
        }
        visitedLetters[letter] = 1;
        DFS(nextRow, nextCol, moves + 1);
        visitedLetters[letter] = 0;
    }
    if (moves > maxMoves){
        maxMoves = moves;
    }
}

int main()
{
    scanf("%d %d", &rows, &columns);
    int row;
    for (row = 0; row < rows; row++){
        scanf("%s", board[row]);
    }
    visitedLetters[board[0][0] - 'A'] = 1;
    DFS(0, 0, 1);
    printf("%d", maxMoves);
    return 0;
}

你可能感兴趣的:(poj,game,DFS,letter,1154)