UVa 439 - Knight Moves

/**
  *  @Author: Pranta Sarker
  *
  **/

#include<bits/stdc++.h>
using namespace std;

#define sf scanf
#define pf printf

int move_x[8] = {2, 1, -1, -2, -2, -1,  1,  2};
int move_y[8] = {1, 2,  2,  1, -1, -2, -2, -1};

int visited[10][10], s_row=0, s_col=0, d_row=0, d_col=0;
int cost[10][10];

void BFS(int r, int c)
{
    visited[r][c] = 1;
    cost[r][c] = 0;

    queue<int>Q;

    Q.push(r);
    Q.push(c);

    while(!Q.empty())
    {
        int ux = Q.front();
        Q.pop();
        int uy = Q.front();
        Q.pop();

        for(int i=0; i<8; i++)
        {
            int vx = ux + move_x[i];
            int vy = uy + move_y[i];

            if((vx > 0 && vx <= 8) && (vy >0 && vy <= 8) && !visited[vx][vy])
            {
                cost[vx][vy] = cost[ux][uy] + 1;
                visited[vx][vy] = 1;
                Q.push(vx);
                Q.push(vy);
            }
        }
    }
}

void CLR()
{
    for(int i=0; i<10; i++)
    {
        for(int j=0; j<10; j++)
        {
            visited[i][j] = 0;
            cost[i][j] = 0;
        }
    }
}

int main()
{
    char ch1, ch2;
    int row1, row2;
    int col1, col2;

    while(sf(" %c %d %c %d", &ch1, &col1, &ch2, &col2)==4)
    {
        s_row = (ch1 - 'a') + 1;
        s_col = col1;

        d_row = (ch2 - 'a') + 1;
        d_col = col2;

        //cout << s_row << " " << s_col << " - " << d_row << " " << d_col << "\n";


        CLR();

        BFS(s_row, s_col);

        pf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, col1, ch2, col2, cost[d_row][d_col]);
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number