Ants and Anteaters CodeChef Solution

Problem -Ants and Anteaters CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Ants and Anteaters CodeChef Solution in C++14

#include <bits/stdc++.h>
using namespace std;
//order_of_key (k) : Number of items strictly smaller than k .
//find_by_order(k) : K-th element in a set (counting from zero).
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
const double pi = 3.14159265358979;
const long long mod=1e9+7;
#define inf 0x3f3f3f3f
#define endl "\n";
#define int long long
vector<int> sieve(int n) {int*arr = new int[n + 1](); vector<int> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
int binpow(int a,int b,int m){a=a%m; int res=1;while(b>0){ if(b&1) res=res*a%m; a=a*a%m; b>>=1; }return res;}
bool isvowel(char v) { return (0x208222>>(v&0x1f))&1;}
bool ispowerof2(int n){ if(n<=0) return false; if((n&(n-1))==0) return true; return false;}
bool onesInBinaryRep(int n){ int cnt=0; while(n>0){ n=n&(n-1); cnt++;} if(cnt%2==0) return true; return false; }
int ceil(int x,int y){ return (x+y-1)/y;}
void solve(){
    int n,m; cin>>n>>m;
    vector<vector<char>> v(n,vector<char>(m));
    for(int i=0; i<n; i++){
        string s; cin>>s;
        for(int j=0; j<m; j++)
            v[i][j]=s[j];
    }
    int ans=0;
    queue<pair<pair<int,int>,char>> q;
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            if(v[i][j]!='-' && v[i][j]!='#'){
                q.push({{i,j},v[i][j]});
            }
        }
    }
    while(!q.empty()){
        int sz=q.size();
        map<pair<int,int>,int> mp;
        for(int i=0; i<sz; i++){
            pair<pair<int,int>,char> p=q.front(); q.pop();
            int x=p.first.first; int y=p.first.second;
            char z=p.second;
            if(z=='D'){
                if(x+1<n){
                    if(v[x+1][y]!='#'){
                        mp[{x+1,y}]++;
                        q.push({{x+1,y},z});
                    }
                }
            }
            else if(z=='U'){
                if(x-1>=0){
                    if(v[x-1][y]!='#'){
                        mp[{x-1,y}]++;
                        q.push({{x-1,y},z});
                    }
                }
            }
            else if(z=='L'){
                if(y-1>=0){
                    if(v[x][y-1]!='#'){
                        mp[{x,y-1}]++;
                        q.push({{x,y-1},z});
                    }
                }
            }
            else if(z=='R'){
                if(y+1<m){
                    if(v[x][y+1]!='#'){
                        mp[{x,y+1}]++;
                        q.push({{x,y+1},z});
                    }
                }
            }
        }
        for(auto it : mp){
            if(it.second>=2){
                ans+=it.second*(it.second-1);
            }
        }
    }
    cout<<ans/2<<endl;
}
signed main()      
{
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t; cin>>t;
    while(t--){
        solve();
    }
}

Ants and Anteaters CodeChef Solution in PYTH 3

# cook your dish here
test = int(input())

for _ in range(test):
    R, C = list(map(int, input().split()))
    grid = []
    R_list = []
    L_list = []
    U_list = []
    D_list = []
    pairs = 0
    for i in range(R):
        row = list(input())
        R_list.append(list((i for i,value in enumerate(row) if value == "R")))
        L_list.append(list((i for i,value in enumerate(row) if value == "L")))
        U_list.append(list((i for i,value in enumerate(row) if value == "U")))
        D_list.append(list((i for i,value in enumerate(row) if value == "D")))
        grid.append(row)
    for i in range(max(R, C)):
        for j in range(len(R_list)):
            for x in range(len(R_list[j])):
                if R_list[j][x] + 1 >= C:
                    R_list[j][x] = "-"
                elif grid[j][R_list[j][x] + 1] == "#":
                    R_list[j][x] = "-"
                else:
                    R_list[j][x] = R_list[j][x] + 1
            R_list[j] = list(filter(("-").__ne__, R_list[j]))
        for j in range(len(L_list)):
            for x in range(len(L_list[j])):
                if L_list[j][x] - 1 < 0:
                    L_list[j][x] = "-"
                elif grid[j][L_list[j][x] - 1] == "#":
                    L_list[j][x] = "-"
                else:
                    L_list[j][x] = L_list[j][x] - 1
            L_list[j] = list(filter(("-").__ne__, L_list[j]))
        for j in range(len(U_list)):
            for x in range(len(U_list[j])):
                if j == 0:
                    U_list[j][x] = "-"
                elif grid[j - 1][U_list[j][x]] == "#":
                    U_list[j][x] = "-"
                else:
                    U_list[j - 1].append(U_list[j][x])
                    U_list[j][x] = "-"
            U_list[j] = list(filter(("-").__ne__, U_list[j]))
                
        for j in range(len(D_list)):
            for x in range(len(D_list[j])):
                if isinstance(D_list[j][x], str):
                    continue
                if j == R - 1:
                    D_list[j][x] = "-"
                elif grid[j + 1][D_list[j][x]] == "#":
                    D_list[j][x] = "-"
                else:
                    D_list[j + 1].append(str(D_list[j][x]))
                    D_list[j][x] = "-"
            D_list[j] = list(filter(("-").__ne__, D_list[j]))
        for k in range(R):
            D_list[k] = list(map(int, D_list[k]))
        for k in range(R):
            if len(R_list[k]) != 0 and len(L_list[k]) != 0:
                s1 = set(R_list[k])
                s2 = set(L_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
            if len(R_list[k]) != 0 and len(D_list[k]) != 0:
                s1 = set(R_list[k])
                s2 = set(D_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
            if len(R_list[k]) != 0 and len(U_list[k]) != 0:
                s1 = set(R_list[k])
                s2 = set(U_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
            if len(L_list[k]) != 0 and len(D_list[k]) != 0:
                s1 = set(L_list[k])
                s2 = set(D_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
            if len(L_list[k]) != 0 and len(U_list[k]) != 0:
                s1 = set(L_list[k])
                s2 = set(U_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
            if len(U_list[k]) != 0 and len(D_list[k]) != 0:
                s1 = set(U_list[k])
                s2 = set(D_list[k])
                set1 = s1.intersection(s2)
                pairs += len(list(set1))
    print(pairs)
        
        
        

Ants and Anteaters CodeChef Solution in C

#include <stdio.h>
char s[50][50];
int r,c;
int valid(int i,int j)
{
	if(i>=0&&i<=r-1&&j>=0&&j<=c-1&&s[i][j]!='#')
		return 1;
	else
		return 0;
}
int main()
{
	int t,i,j,k,up,down,right,left,l,meet;
	scanf("%d",&t);
	for(k=0;k<t;k++)
	{
		scanf("%d%d",&r,&c);
		for(j=0;j<r;j++)
			scanf("%s",s[j]);
		meet=0;
		for(i=0;i<r;i++)
		{
			for(j=0;j<c;j++)
			{
				up=1;
				down=1;
				right=1;
				left=1;
				l=1;
				if(s[i][j]=='#')
					continue;
				while(up||down||right||left)
				{
					if(!valid(i-l,j))
						up=0;
					if(!valid(i+l,j))
						down=0;
					if(!valid(i,j-l))
						left=0;
					if(!valid(i,j+l))
						right=0;
					if(up&&down&&s[i-l][j]=='D'&&s[i+l][j]=='U')
						meet++;
					if(up&&right&&s[i-l][j]=='D'&&s[i][j+l]=='L')
						meet++;
					if(up&&left&&s[i-l][j]=='D'&&s[i][j-l]=='R')
						meet++;
					if(down&&left&&s[i+l][j]=='U'&&s[i][j-l]=='R')
						meet++;
					if(down&&right&&s[i+l][j]=='U'&&s[i][j+l]=='L')
						meet++;
					if(right&&left&&s[i][j+l]=='L'&&s[i][j-l]=='R')
						meet++;					
					l++;
				}
			}
		}
		printf("%d\n",meet);
	}
	return 0;
}

Ants and Anteaters CodeChef Solution in JAVA

import java.io.*;
import java.util.*;
class anteater {
    public static void main(String[] args)throws IOException {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int z=1;z<=t;z++){
            int n=sc.nextInt();
            int m=sc.nextInt();
            char ch[][]=new char[n][m];
            int count[][][]=new int[n][m][51];
            for(int i=0;i<n;i++){
                String s=sc.next();
                for(int j=0;j<m;j++){
                    ch[i][j]=s.charAt(j);
                }
            }

            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(ch[i][j]=='R'){
                        update(count,0,1,n,m,i,j,ch);
                    }
                    else if(ch[i][j]=='L'){
                        update(count,0,-1,n,m,i,j,ch);
                    }
                    else if(ch[i][j]=='U'){
                        update(count,-1,0,n,m,i,j,ch);
                    }
                    else if(ch[i][j]=='D') {
                        update(count,1,0,n,m,i,j,ch);
                    }
                }
            }
            int pairs=0;
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(ch[i][j]!='#')
                    {
                    //System.out.println(i+" "+j);
                        for(int k=0;k<=50;k++){
                            //System.out.print(count[i][j][k]+" ");
                            int tt=count[i][j][k];
                            pairs+=((tt*(tt-1))/2);
                        }
                        //System.out.println();
                    
                    }
                }
            }
            System.out.println(pairs);
        }
    }
    static void update(int a[][][],int r,int c,int n,int m,int i,int j,char ch[][]){
        int cc=0;
        while(i<n && j<m && i>=0 && j>=0){
            if(ch[i][j]=='#'){
                break;
            }
            a[i][j][cc]++;
            i+=r;
            j+=c;
            cc++;
        }
    }    
}

Ants and Anteaters CodeChef Solution in PYPY 3

from collections import Counter
def binomialCoef(n, k): 
    C = [[0 for x in range(k+1)] for x in range(n+1)] 
  
    # Calculate value of Binomial Coefficient in bottom up manner 
    for i in range(n+1): 
        for j in range(min(i, k)+1): 
            # Base Cases 
            if j == 0 or j == i: 
                C[i][j] = 1
  
            # Calculate value using previously stored values 
            else: 
                C[i][j] = C[i-1][j-1] + C[i-1][j] 
  
    return C[n][k] 

for _ in range(int(input())):
    r,c=map(int,input().split())
    d=dict()
    grid=[None]*r
    for i in range(r):
        grid[i]=input()
    for i in range(r):
        for j in range(c):
            if grid[i][j]=="U":
                kk=i
                sec=0
                while kk>=0:
                    if grid[kk][j]=="#":
                        break
                    try:
                        d["r"+str(kk)+"c"+str(j)].append(sec)
                    except:
                        d["r"+str(kk)+"c"+str(j)]=[sec]
                    sec+=1
                    kk-=1
            if grid[i][j]=="D":
                kk=i
                sec=0
                while kk<r:
                    if grid[kk][j]=="#":
                        break
                    try:
                        d["r"+str(kk)+"c"+str(j)].append(sec)
                    except:
                        d["r"+str(kk)+"c"+str(j)]=[sec]
                    sec+=1
                    kk+=1
            if grid[i][j]=="R":
                kk=j
                sec=0
                while kk<c:
                    if grid[i][kk]=="#":
                        break
                    try:
                        d["r"+str(i)+"c"+str(kk)].append(sec)
                    except:
                        d["r"+str(i)+"c"+str(kk)]=[sec]
                    sec+=1
                    kk+=1
            if grid[i][j]=="L":
                kk=j
                sec=0
                while kk>=0:
                    if grid[i][kk]=="#":
                        break
                    try:
                        d["r"+str(i)+"c"+str(kk)].append(sec)
                    except:
                        d["r"+str(i)+"c"+str(kk)]=[sec]
                    sec+=1
                    kk-=1

    ans=0
    for i in d.values():
        f=dict(Counter(i))
        for j in f.values():
            ans+=binomialCoef(j,2)
    print(ans)
                            
                

Ants and Anteaters CodeChef Solution in PYTH

from collections import defaultdict
t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	R = int(st[0])
	C = int(st[1])
	A = []
	S = set()
	for y in range(R+2):
		S.add((y,0))
		S.add((y,C+1))
	# endfor y
	for x in range(C+2):
		S.add((0,x))
		S.add((0,R+1))
	# endfor x
	for y in range(1,R+1):
		st = raw_input().strip()
		for x in range(1,C+1):
			ch = st[x-1]
			if ch == '#':
				S.add((y,x))
			elif ch == 'U':
				A.append([y,x,-1,0])
			elif ch == 'D':
				A.append([y,x,1,0])
			elif ch == 'L':
				A.append([y,x,0,-1])
			elif ch == 'R':
				A.append([y,x,0,1])
			# endif
		# endfor x
	# endfor y
	num = min(R,C) -1
	num = max(num,R/2,C/2)
	tot = 0
	sz = len(A)
	for k in range(num):
		G= [[0 for x in range(C+1)] for y in range(R+1)]
		D = defaultdict(int)
		p = 0
		while p < sz:
			y = A[p][0]+A[p][2]
			x = A[p][1]+A[p][3]
			if not (y,x) in S:
				tot += D[y,x]
				D[y,x] += 1
				A[p][0] = y
				A[p][1] = x
			else:
				del(A[p])
				sz -= 1
				p -= 1
			# endif
			p += 1
		# endwhile
	# endfor k
	print tot
# endfor i

Ants and Anteaters CodeChef Solution in GO

package main
import "fmt"
import "io"
import "math"
import "os"

func main() {
	T := ScanInt(1, 10)
	for t := 1; t <= T; t++ {
		solve()
	}
}

var g1, g2 [50][50]byte

const (
	up = 1 << iota
	down
	right
	left
	eater
)

var bits = []int{
	0, 1, 1, 2,
	1, 2, 2, 3,
	1, 2, 2, 3,
	2, 3, 3, 4,
}

func solve() {
	NewLine()
	R := ScanInt(1, 50)
	C := ScanInt(1, 50)
	grid := &g1
	for r := 0; r < R; r++ {
		NewLine()
		row := ScanString(C, C)
		for c := 0; c < C; c++ {
			switch row[c] {
			case 'U':
				grid[r][c] = up
			case 'D':
				grid[r][c] = down
			case 'R':
				grid[r][c] = right
			case 'L':
				grid[r][c] = left
			case '#':
				grid[r][c] = eater
			case '-':
				grid[r][c] = 0
			default:
				panic("bad input")
			}
		}
	}
	next := &g2
	count := 0
	for moving := true; moving; {
		moving = false
		for r := 0; r < R; r++ {
			for c := 0; c < C; c++ {
				if grid[r][c] == eater {
					next[r][c] = eater
				} else {
					next[r][c] = 0
				}
			}
		}
		enter := func(r, c int, dir byte) {
			if 0 <= r && r < R && 0 <= c && c < C && next[r][c] != eater {
				next[r][c] |= dir
				if next[r][c] != 0 {
					moving = true
				}
			}
		}
		for r := 0; r < R; r++ {
			for c, cell := range grid[r][:C] {
				if cell & up != 0 {
					enter(r - 1, c, up)
				}
				if cell & down != 0 {
					enter(r + 1, c, down)
				}
				if cell & left != 0 {
					enter(r, c - 1, left)
				}
				if cell & right != 0 {
					enter(r, c + 1, right)
				}
			}
		}
		grid, next = next, grid
		for r := 0; r < R; r++ {
			for _, cell := range grid[r][:C] {
				if cell < eater {
					n := bits[cell]
					count += n * (n - 1) / 2
				}
			}
		}
	}
	fmt.Println(count)
}
func ScanInt(low, high int) int {
	return int(ScanInt64(int64(low), int64(high)))
}
func NewLine() {
	if CheckInput {
		for n, b := range RemainingInput {
			if b != ' ' && b != '\t' && b != '\r' {
				Assert(b == '\n')
				RemainingInput = RemainingInput[n+1:]
				return
			}
		}
		Assert(false)
	}
}
func ScanString(short, long int) string {
	return string(ScanBytes(short, long))
}
func ScanInt64(low, high int64) int64 {
	x := Btoi(ScanToken())
	Assert(low <= x && x <= high || !CheckInput)
	return x
}
func Assert(condition bool) {
	if !condition {
		panic("assertion failed")
	}
}
func ScanBytes(short, long int) []byte {
	token := ScanToken()
	Assert(short <= len(token) && len(token) <= long)
	return token
}

func Btoi(s []byte) int64 {
	if s[0] == '-' {
		x := Btou(s[1:])
		Assert(x <= - math.MinInt64)
		return - int64(x)
	} else {
		x := Btou(s)
		Assert(x <= math.MaxInt64)
		return int64(x)
	}
}

var RemainingInput []byte
var CheckInput = true

func ScanToken() []byte {
	chunk := 1 << 16
	skipws: for {
		for n, b := range RemainingInput {
			if b != ' ' && b != '\t' && b != '\r' {
				if b == '\n' && CheckInput {
					panic("ScanToken: reached end of line")
				}
				RemainingInput = RemainingInput[n:]
				break skipws
			}
		}
		if len(RemainingInput) == 0 {
			RemainingInput = make([]byte, chunk)
			n, e := os.Stdin.Read(RemainingInput)
			if e != nil && e != io.EOF {
				panic(e)
			}
			if n == 0 {
				panic("ScanToken: reached EOF")
			}
			RemainingInput = RemainingInput[:n]
		}
	}

	n := 1
	for {
		if n == len(RemainingInput) {
			ri := make([]byte, 2 * n + chunk)
			copy(ri, RemainingInput)
			k, e := os.Stdin.Read(ri[n:])
			if e != nil && e != io.EOF {
				panic(e)
			}
			RemainingInput = ri[:n+k]
			if k == 0 {
				if CheckInput {
					panic("ScanToken: EOF in middle of token")
				} else {
					break // and pray
				}
			}
		}
		b := RemainingInput[n]
		if b == ' ' || b == '\t' || b == '\r' || b == '\n' {
			break
		}
		n++
	}
	token := RemainingInput[:n]
	RemainingInput = RemainingInput[n:]
	return token
}

func Btou(s []byte) uint64 {
	Assert(len(s) > 0)
	var x uint64
	for _, d := range s {
		Assert('0' <= d && d <= '9')
		d -= '0'
		if x >= math.MaxUint64 / 10 {
			Assert(x == math.MaxUint64 / 10 && d <= math.MaxUint64 % 10)
		}
		x = x * 10 + uint64(d)
	}
	return x
}
Ants and Anteaters CodeChef Solution Review:

In our experience, we suggest you solve this Ants and Anteaters CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Ants and Anteaters CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Ants and Anteaters CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *