%Problem 6
n=100; %the dimensions of the lattice

A=sparse([],[],[],n^2,n^2,5*n^2);
%Each row of A corresponds to a node in the lattice

ind = @(i,j) (i-1)*n+j;
%the function "ind" translates an (i, j) position in the lattice to a row
%and column index within the matrix A corresponding to the node at (i,j)

%for example:
%In a 3x3 lattice, the location (i, j)=(3, 2) in the lattice corresponds
%to node 8 which is represented by row and column 8 in matrix A.

%Iterate through the nodes:
for i=1:n
    for j=1:n
        c= ind(i,j);
        %We now fill in row 'c' of the matrix corresponding to node 'c'
        if(i==1 && j==1) || (i==n && j==n) %'c' is the first or last node
            A(c, c)=1;
            continue
        end
      
        if i>1 %node 'c' is not on the bottom row of the lattice
            A(c,c)=A(c,c)-1; %iterate the value of the diagonal by -1
            A(c, ind(i-1, j))= 1; %add 1 in the col of the node below 'c'
        end
        
        if i<n %node 'c' is not on the top row of the lattice
            A(c,c)=A(c,c)-1; %iterate the value of the diagonal by -1
            A(c, ind(i+1, j))= 1; %add 1 in the col of the node above 'c'
        end

        if j>1 %node 'c' is not in the leftmost column of the lattice
            A(c,c)=A(c,c)-1; %iterate the value of the diagonal by -1
            A(c, ind(i, j-1))= 1; %add 1 in the col of the node left of 'c'
        end

        if j<n %node 'c' is not in the rightmost column of the lattice
            A(c,c)=A(c,c)-1; %iterate the value of the diagonal by -1
            A(c, ind(i, j+1))= 1; %add 1 in the col of the node right of 'c'
        end
    end
end

b=zeros(n^2,1);
b(1)=1;

tic
y=A\b;
toc
v50=sprintf('%0.6f',y(50^2));